使用字符串分隔符(标准C ++)解析(拆分)C ++中的字符串 [英] Parse (split) a string in C++ using string delimiter (standard C++)
问题描述
可能重复:
使用C ++拆分字符串
在C ++中使用以下内容:
I am parsing a string in C++ using the following:
string parsed,input="text to be parsed";
stringstream input_stringstream(input);
if(getline(input_stringstream,parsed,' '))
{
// do some processing.
}
使用单个字符分隔符解析即可。
Parsing with a single char delimiter is fine. But what if I want to use a string as delimiter.
例如:我要分割:
scott>=tiger
得到斯科特和老虎。
推荐答案
您可以使用 std :: string :: find()
函数找到字符串分隔符的位置,然后使用 std :: string :: substr()
以获取令牌。
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 s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
-
$ c> find(const string& str,size_t pos = 0)函数返回字符串中
str
的第一次出现的位置,如果找不到字符串,请npos
。The
find(const string& str, size_t pos = 0)
function returns the position of the first occurrence ofstr
in the string, ornpos
if the string is not found.substr(size_t pos = 0,size_t n = npos)
函数返回子字符串pos
和长度npos
开始的对象。The
substr(size_t pos = 0, size_t n = npos)
function returns a substring of the object, starting at positionpos
and of lengthnpos
.如果您有多个分隔符,则在提取一个令牌后,可以将其删除后续提取(如果要保留原始字符串,只需使用
s = s.substr(pos + delimiter.length());
):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.erase(0, s.find(delimiter) + delimiter.length());
这样,您就可以轻松地循环获取每个令牌。
This way you can easily loop to get each 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
这篇关于使用字符串分隔符(标准C ++)解析(拆分)C ++中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!