C++ 标记字符串

2021-12-28 00:00:00 string split token c++

我正在寻找一种简单的方法来标记字符串输入,而无需使用非默认库,例如 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;
}

相关文章