从不带空格的字符串中读取整数
Reading integers from a string with no space
我正试图从字符串中读取数字,例如:如果
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上的实例。
是的,你可以为这个写你自己的循环,但是:
- 你可能会犯一些愚蠢的错误,
- 正则表达式可以适应许多不同的搜索模式;例如,如果TMR决定要支持十进制/负数/浮点数,该怎么办?这些情况和许多其他情况将很容易支持一个正则表达式,可能不是那么多与您的自定义解决方案:)
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 从二进制文件中读取整数数组
- 使用字符串流读取整数并将它们相加
- 如何在从文件中读取整数时使用 file.eof()?
- C++从键盘读取整数的功能
- 为什么字符串流只读取整数中的第一个数字?如何使它只在空白处移动?
- 如何从文本文件C++读取整数和特殊字符
- C++ 从控制台读取整数数组
- 从文本文件中读取整数并将它们存储到数组中
- 输入重定向读取整数和char C
- 从文件读取整数到矩阵 (c++)
- 如何读取整数直到线结束
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 从文本文件中读取整数
- 读取整数对,直到文本输入文件中的换行符
- 在C++中从文件中读取整数和字符
- 使用 MFC C++ 6.0 从 ms 访问中读取整数数据
- 从标准输入和输入值中读取整数到向量
- 从文件中读取整数到数组