【问题标题】:Parse int from a string without regex?从没有正则表达式的字符串中解析int?
【发布时间】:2020-08-25 09:21:25
【问题描述】:

如果我有一个包含单词和数字的字符串(例如“Text 125”),是否可以在不使用正则表达式的情况下获取该数字并将其转换为 int?

【问题讨论】:

    标签: c++ string c++11


    【解决方案1】:

    是的,如果您知道stringstream 是一个单词后跟一个数字,那么您可以使用它。

    std::stringstream ss("Text 125"); 
    std::string buffer; //a buffer to read "Text" into
    int n; //to store the number in
    
    ss >> buffer >> n; //reads "Text" into buffer and puts the number in n
    std::cout << n << "\n";
    

    编辑:我找到了一种无需声明无意义变量的方法。虽然它有点不那么健壮。此版本假定数字后面没有任何内容。无论单词和数字之间有多少空格,std::stoi 都会起作用。

    std::string str("Text 125");
    int n = std::stoi(str.substr(str.find_first_of(' ') + 1));
    std::cout << n << std::endl;
    

    【讨论】:

    • 感谢您的回答!可惜我不能写 ss >> string() >> n;因为我在任何地方都不需要那个字符串
    【解决方案2】:

    如果您完全了解预期字符串的格式,即它

    • 始终以“文本”开头
    • 后跟一个空格
    • 后跟一个数字
    • 然后结束
    • (所以在正则表达式中,它是/^Text (\d+)$/

    您可以组合std::findstd::substr

      const std::string inputStr = "Text 125";
      const std::string textStr = "Text ";
    
      const std::size_t textPos = inputStr.find(textStr);
      const std::size_t numberPos = textPos + textStr.length();
      const std::string numberStr = inputStr.substr(numberPos);
      const int numberInt = std::atoi(numberStr.c_str());         
    

    但是,这只适用于这些特定情况。即使/^Text (\d+)$/ 是唯一的预期格式,其他输入字符串可能仍然存在,因此您需要添加适当的长度检查,然后抛出异常或返回无效数字或您需要为无效输入字符串发生的任何事情。

    @DanielGiger 的回答更普遍适用。 (只要求数字是第二个字符串,涵盖/^\S+\s+(\d+)/这种更一般的情况)

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 2021-10-05
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2016-04-29
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多