C++ 标记字符串

C++ Tokenize String(C++ 标记字符串)

本文介绍了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;
}

这篇关于C++ 标记字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 标记字符串

基础教程推荐