【问题标题】:C++ Tokenize StringC++ 标记字符串
【发布时间】:2012-04-20 13:19:31
【问题描述】:

我正在寻找一种不使用非默认库(如 Boost 等)来标记字符串输入的简单方法。

例如,如果用户输入了 40_5,我想用 _ 作为分隔符来分隔 40 和 5。

【问题讨论】:

标签: c++ string split token


【解决方案1】:

查看this 教程,这是迄今为止我发现的关于标记化的最佳教程。它涵盖了实现不同方法的最佳实践,包括在 C++ std 中使用 getline()find_first_of() 以及 strtok()在 C 中。

【讨论】:

    【解决方案2】:

    将字符串转换为标记向量(线程安全):

    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;
    }
    

    【讨论】:

    • +1 比我链接到的 strstream 的东西更有吸引力。
    • 像魅力一样工作。使用const string &amp;delimiter 作为第二个参数似乎也可以。
    【解决方案3】:

    您可以使用strtok_r 函数,但请仔细阅读手册页,以便了解它如何维护状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多