C++ 标记字符串

问题描述 投票:0回答:4

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

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

c++ string split token
4个回答
26
投票

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

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
投票

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


1
投票

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


0
投票
现代 C++ | C++20

#include <string> #include <ranges> #include <vector> int main() { std::string input = "C++20 Tokenization Example"; auto space_split = input | std::views::split(' '); std::vector<std::string> tokens; for (const auto& token_range : space_split) { std::string token; std::ranges::copy(token_range, std::back_inserter(token)); tokens.push_back(token); } }
    
© www.soinside.com 2019 - 2024. All rights reserved.