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

what is the best way to parse a string in c++

本文关键字:最佳 方法 是什么 字符串 C++      更新时间:2023-10-16

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

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

当然,我们对字符串名称和值感兴趣。我们的目标是将字符串和值保存在映射中。有没有一种自动方法可以将字符串放在括号内?

谢谢

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

#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)作为分隔符来构建更复杂的东西。

下面就可以了:

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;
}