Warm tip: This article is reproduced from serverfault.com, please click

parsing-使用字符串定界符(标准C ++)解析(分割)C ++中的字符串

(parsing - Parse (split) a string in C++ using string delimiter (standard C++))

发布于 2013-01-10 19:16:43

我正在使用以下方法在C ++中解析字符串:

using namespace std;

string parsed,input="text to be parsed";
stringstream input_stringstream(input);

if (getline(input_stringstream,parsed,' '))
{
     // do some processing.
}

使用单个字符定界符进行解析就可以了。但是,如果我想使用字符串作为分隔符怎么办。

示例:我想拆分:

scott>=tiger

>=作为分隔符,以便我可以得到斯科特和老虎。

Questioner
TheCrazyProgrammer
Viewed
0
Vincenzo Pii 2013-09-16 16:18:09

你可以使用该std::string::find()函数查找字符串定界符的位置,然后使用std::string::substr()来获取标记。

例子:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • find(const string& str, size_t pos = 0)函数返回str字符串中第一次出现的位置,或者返回npos未找到字符串的位置。

  • substr(size_t pos = 0, size_t n = npos)函数返回对象的子字符串,从positionpos和length开始npos


如果有多个定界符,则在提取了一个标记之后,可以将其删除(包括定界符)以进行后续提取(如果要保留原始字符串,只需使用s = s.substr(pos + delimiter.length());):

s.erase(0, s.find(delimiter) + delimiter.length());

这样,你可以轻松地循环获取每个令牌。

完整的例子

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    std::cout << token << std::endl;
    s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

输出:

scott
tiger
mushroom