如何用整数解析字符串?

时间:2018-05-05 15:56:03

标签: c++ string parsing stringstream string-parsing

我有字符串

str="1Apple2Banana3Cat4Dog";

如何将此字符串解析为

Apple
Banana
Cat
Dog

我使用了stringstream,如下所示,但没有用

stringstream ss(str);
int i;
while(ss>>i)
{
     ss>>s;
     cout<<s<<endl;
}

输出是:

Apple2Banana3Cat4Dog

这不是预期的, 有人帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以使用std::regex

#include <iostream>
#include <regex>

std::string str{"1Apple2Banana3Cat4Dog"};

int main() {
    std::regex e{ "[0-9]{1}([a-zA-Z]+)" };
    std::smatch m;
    while (std::regex_search(str, m, e)) {
        std::cout << m[1] << std::endl;
        str = m.suffix().str();
    }
}

输出:

Apple
Banana
Cat
Dog

答案 1 :(得分:0)

请参阅此代码段(适用于水果数量0-9):

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(){

    const string str = "1Apple2Banana3Cat4Dog";
    vector<int> pts;

    // marked integer locations
    for (int i = 0; i < str.size(); i++)
    {
        int r =  str[i] ; 
        if (r >= 48 && r <= 57)  // ASCII of 0 = 48 and ASCII of 9 = 57
        { 
            pts.push_back(i);
        }
    }

    // split string 
    for (int i = 0; i < pts.size(); i++)
    {
        string st1;
        if( i == pts.size()-1)
            st1 = str.substr(pts[i] + 1, (pts.size() - 1) - (pts[i] + 1));
        else
         st1 = str.substr(pts[i]+1, (pts[i+1])-(pts[i]+1) ); 
        cout << st1 << "  ";
    }       

    return 0;
}

输出:

enter image description here