从不带空格的字符串中读取整数

Reading integers from a string with no space

本文关键字:读取 整数 字符串 空格      更新时间:2023-10-16

我正试图从字符串中读取数字,例如:如果

string str = "1Hi15This10";

我想得到(1,15,10)

我尝试通过索引,但我读取10为1和0不是10。我不能使用getline,因为字符串没有被任何东西分开。

任何想法?

不使用正则表达式也可以这样做

std::string str = "1Hi15This10";
for (char *c = &str[0]; *c; ++c)
   if (!std::isdigit(*c) && *c != '-' && *c != '+') *c = ' ';

整数现在由空格分隔符分隔,这对于解析

来说是微不足道的。

恕我直言,最好的方法是使用正则表达式。

#include <iostream>
#include <iterator>
#include <string>
#include <regex>
int main() {
    std::string s = "1Hi15This10";
    std::regex number("(\d+)");  // -- match any group of one or more digits
    auto begin = std::sregex_iterator(s.begin(), s.end(), number);
    // iterate over all valid matches  
    for (auto i = begin; i != std::sregex_iterator(); ++i) {
        std::cout << "  " << i->str() << 'n';
        // and additional processing, e.g. parse to int using std::stoi() etc.
    }
}
输出:

  1
  15
  10

ideone上的实例。

是的,你可以为这个写你自己的循环,但是:

  1. 你可能会犯一些愚蠢的错误,
  2. 正则表达式可以适应许多不同的搜索模式;例如,如果TMR决定要支持十进制/负数/浮点数,该怎么办?这些情况和许多其他情况将很容易支持一个正则表达式,可能不是那么多与您的自定义解决方案:)