我正在使用以下代码在 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
以 >=
作为分隔符,这样我就可以得到 scott 和 Tiger。
最佳答案
您可以使用 std::string::find()
函数查找字符串分隔符的位置,然后使用 std::string::substr()
获取 token 。
例子:
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)
函数返回对象的子字符串,从位置 pos
开始,长度为 npos
.
如果您有多个分隔符,在提取一个标记后,您可以将其删除(包括分隔符)以继续进行后续提取(如果您想保留原始字符串,只需使用 s = s.substr( pos + delimiter.length());
):
s.erase(0, s.find(delimiter) + delimiter.length());
这样您就可以轻松循环获取每个 token 。
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
https://stackoverflow.com/questions/14265581/