我正在寻找一种简单的方法来对
例如,如果用户输入forty_five,我希望使用'_'作为分隔符来分离'forty'和'five'。
std::string
输入进行标记化,而不使用非默认库,如Boost等。例如,如果用户输入forty_five,我希望使用'_'作为分隔符来分离'forty'和'five'。
将一个字符串转换为一个令牌向量(线程安全):
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;
}
const string &delimiter
作为第二个参数似乎也可以。 - sotrh#include <string>
#include <ranges>
#include <algorithm>
#include <iostream>
int main()
{
const std::string input{ "C++20 Tokenization Example" };
for (const auto& token_range : input | std::views::split(' ')) {
std::string token{};
std::ranges::copy(token_range, std::back_inserter(token));
std::cout << token << std::endl;
}
}
输出:
C++20
Tokenization
Example
看看this教程,这是目前我发现的最好的分词教程。它涵盖了在C++ std中使用getline()和find_first_of(),以及在C中使用strtok()等不同方法实现的最佳实践。