什么是在c ++中解析字符串的最佳方法

时间:2014-12-07 13:37:11

标签: c++ parsing

如何最好地解析c ++中的以下字符串: 输入是一个字符串,例如:

(someString1 45)(someString2 2432)(anotherString 55)  // .... etc.

当然我们对字符串名称和值感兴趣.. 我们的目标是将字符串和值保存在地图中。 是否有自动方式将字符串放在括号内?

谢谢,

2 个答案:

答案 0 :(得分:1)

如果你的字符串不包含空格,这是一个简单的解决方案:

#include <iostream>
#include <string>

int main()
{
    char c1, c2;
    int n;
    std::string s;
    while (std::cin >> c1 >> s >> n >> c2 && c1 == '(' && c2 == ')')
    {
        std::cout << "Parse item: s = '" << s << "', number = " << n << "\n";
    }
}

此方法仅适用于正确的输入,无法在中途恢复。如果您需要,可以使用getline)作为分隔符来构建更精细的内容。

答案 1 :(得分:1)

以下将解决这个问题:

string some;  int n; 
string s = "(someString1 45)(someString2 2432)(anotherString 55)";
stringstream sst(s);   // to parse the string 

while (sst.get() == '(' && sst >> some >> n && sst.get()==')') {
    cout << some << "," << n << endl; 
}

如果不存在开括号,则此循环不会尝试读取某些字符串n

如果您希望某些内容符合大括号之间的条目列表,则稍微更改甚至可以允许安全地解析更多输入字符串:

string s = "(someString1 45)(someString2 2432)(anotherString 55)thats the rest";
...
while (sst.get() == '(') {  // open brace to process
    if (sst >> some >> n && sst.get() == ')') 
        cout << some << "," << n << endl;   // succesful parse of elements
    else {
        cout << "Wrong format !!\n";   // something failed 
        if (!sst.fail()) sst.setf(ios::failbit);  // case of missing closing brace
    }
} 
if (sst) { // if nothing failed, we are here because open brace was missing and there is still input 
    sst.unget();  // ready to parse the rest, including the char that was checked to be a brace
    string rest;
    getline(sst, rest);
    cout << "The braces are followed by:  " << rest << endl;
}