我正在寻找一种简单的方法来标记字符串输入,而无需使用非默认库,例如 Boost 等.
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++ 标记字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!