String Stream in C++ to parse string of words & numbers

爱⌒轻易说出口 提交于 2021-02-18 12:39:06

问题


I have string like this: '123plus43times7'

where numbers are followed by words from a dictionary.

I understand that I can extract int/numbers by using the >> operator:

StringStream >> number

I can get the number. However, the Stream still has the number in it. How do I remove the number when the length of number is unknown or should I find out length of number and then use str.substr() to create a new String Stream ? Any other better method for doing it using C++ STL String and SStream would be really appreciated.


回答1:


You can insert blank space between text and numbers and then use 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;
}



回答2:


here's one way to do it

string as = "123plus43times7";

    for (int i = 0; i < as.length(); ++i)
    {
        if (isalpha(as[i]))
            as[i] = ' ';
    }

    stringstream ss(as);
    int anum;

    while (ss >> anum)
    {
        cout << "\n" << anum;
    }


来源:https://stackoverflow.com/questions/36705943/string-stream-in-c-to-parse-string-of-words-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!