C ++令牌字符串 [英] C++ Tokenize String
本文介绍了C ++令牌字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果用户输入forty_five,那么我们将使用一个简单的方法来对字符串输入进行标记化,而不使用Boost等非默认库。
解决方案
要将一个字符串转换为一个令牌的向量线程安全):
std :: vector< std :: string& inline StringSplit(const std :: string& source,const char * delimiter =,bool keepEmpty = false)
{
std :: vector< std :: string&结果;
size_t prev = 0;
size_t next = 0;
while((next = source.find_first_of(delimiter,prev))!= std :: string :: npos)
{
if(keepEmpty || != 0))
{
results.push_back(source.substr(prev,next - prev));
}
prev = next + 1;
}
if(prev< source.size())
{
results.push_back(source.substr(prev));
}
返回结果;
}
I'm looking for a simple way to tokenize string input without using non default libraries such as Boost, etc.
For example, if the user enters forty_five, I would like to seperate forty and five using the _ as the delimiter.
解决方案
To convert a string to a vector of tokens (thread safe):
std::vector<std::string> inline StringSplit(const std::string &source, const char *delimiter = " ", bool keepEmpty = false)
{
std::vector<std::string> results;
size_t prev = 0;
size_t next = 0;
while ((next = source.find_first_of(delimiter, prev)) != std::string::npos)
{
if (keepEmpty || (next - prev != 0))
{
results.push_back(source.substr(prev, next - prev));
}
prev = next + 1;
}
if (prev < source.size())
{
results.push_back(source.substr(prev));
}
return results;
}
这篇关于C ++令牌字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文