c++ - C++中的字符串流来解析单词和数字的字符串

标签 c++ string stringstream

我有这样的字符串: '123plus43times7'

其中数字后跟字典中的单词。

我知道我可以使用 >>> 运算符提取整数/数字:

StringStream >> number

我可以得到号码。但是, Stream 中仍然有数字。当数字的长度未知时如何删除数字,或者我应该找出数字的长度然后使用 str.substr() 创建一个新的 String Stream ? 使用 C++ STL String 和 SStream 的任何其他更好的方法将不胜感激。

最佳答案

您可以在文本和数字之间插入空格,然后使用 std::stringstream

#include <iostream>
#include <string>
#include <sstream>
#include <cctype>

int main() 
{
    std::string s = "123plus43times7";
    for (size_t i = 0; i < (s.size() -1 ); i++)
    {
        if (std::isalpha(s[i]) != std::isalpha(s[i + 1]))
        {
            i++;
            s.insert(i, " ");
        }
    }
    std::stringstream ss(s);
    while (ss >> s)
        std::cout << s << "\n";
    return 0;
}

关于c++ - C++中的字符串流来解析单词和数字的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36705943/

相关文章:

c++ - C/C++ 中的正则表达式

C++ 字符串在开头和结尾添加

javascript - 如何检查字符串是否以javascript中的数字开头

c++ - 文件输入,尝试从字符串中提取 Int (C++)

c++ - C++ 中 std::cout 的奇怪行为

c++ - 除了 XCode,如何在 OS X 上正确设置 googleTest

c++ - 什么时候应该使用字符串而不是字符串流?

c++ - 有没有办法从 string_view 创建字符串流而不复制数据?

c++ - 从 Visual Studio 2013 转换到 Visual Studio 2015 的问题

java - 如何从文本文件中获取值