我正在使用以下方法在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
与>=
作为分隔符,以便我可以得到斯科特和老虎。
你可以使用该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
对于那些不想修改输入字符串的人,请执行
size_t last = 0; size_t next = 0; while ((next = s.find(delimiter, last)) != string::npos) { cout << s.substr(last, next-last) << endl; last = next + 1; } cout << s.substr(last) << endl;
注意:
mushroom
循环外的输出,即s = mushroom
这些样本不会从字符串中提取最后一个标记。我的示例从一个字符串中提取IpV4:<code> size_t last = 0; size_t next = 0; int索引= 0; while(index <4){next = str.find(delimiter,last); 自动编号= str.substr(last,next-last); IPv4 [index ++] = atoi(number.c_str()); 最后=下一个+ 1; } </ code>
@ hayk.mart请注意,由于分隔符的大小为2个字符,因此需要添加2而不是1 :):std :: string s =“ scott> = tiger> = mushroom”; std :: string分隔符=“> =”; size_t last = 0; size_t next = 0; while((next = s.find(delimiter,last))!= std :: string :: npos){std :: cout << s.substr(last,next-last)<< std :: endl; 最后=下一个+ 2; } std :: cout << s.substr(last)<< std :: endl;
想知道615个支持者中有多少人错过了最后一行,并在其生产代码中运行了隐藏的错误。从评论来看,我至少下注几下。IMO如果不使用此答案
cout
,而是将其显示为功能,则将更适合该答案。