You can use the std::string::find()
function to find the position of your string delimiter, then use std::string::substr()
to get a token.
(您可以使用std::string::find()
函数查找字符串定界符的位置,然后使用std::string::substr()
获得令牌。)
Example:
(例:)
std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
The find(const string& str, size_t pos = 0)
function returns the position of the first occurrence of str
in the string, or npos
if the string is not found.
(find(const string& str, size_t pos = 0)
函数返回str
中第一次出现str
的位置,如果找不到该字符串,则npos
。)
The substr(size_t pos = 0, size_t n = npos)
function returns a substring of the object, starting at position pos
and of length npos
.
(substr(size_t pos = 0, size_t n = npos)
函数返回对象的子字符串,从位置pos
开始,长度为npos
。)
If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());
):
(如果有多个定界符,则在提取了一个标记后,可以将其删除(包括定界符)以进行后续提取(如果要保留原始字符串,只需使用s = s.substr(pos + delimiter.length());
):)
s.erase(0, s.find(delimiter) + delimiter.length());
This way you can easily loop to get each token.
(这样,您可以轻松地循环获取每个令牌。)
Complete Example (完整的例子)
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;
Output:
(输出:)
scott
tiger
mushroom
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…