【问题标题】:how parse the string with integers?如何用整数解析字符串?
【发布时间】:2018-05-05 15:56:03
【问题描述】:

我有字符串

str="1Apple2Banana3Cat4Dog";

如何将这个字符串解析成

Apple
Banana
Cat
Dog

我在下面使用了stringstream,但没有用

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

输出是:

Apple2Banana3Cat4Dog

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

【问题讨论】:

  • 将文本读入字符串。使用状态机收集数字或字母。

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


【解决方案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

【讨论】:

    【解决方案2】:

    查看这个 sn-p(应该适用于水果数量 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;
    }
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 2012-06-27
      • 2010-10-03
      相关资源
      最近更新 更多