C++ 分割字符串

15
我正在寻找一种简单的方法来对std::string输入进行标记化,而不使用非默认库,如Boost等。
例如,如果用户输入forty_five,我希望使用'_'作为分隔符来分离'forty'和'five'。

1
可能是如何在C++中对字符串进行分词?的重复问题。 - Corbin
https://dev59.com/k3VC5IYBdhLWcg3wnCj6#236803 - ergosys
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 比我链接的 strstream 更具吸引力。 - ergosys
运行得非常好。使用 const string &delimiter 作为第二个参数似乎也可以。 - sotrh

2
C++20
#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

演示


0

看看this教程,这是目前我发现的最好的分词教程。它涵盖了在C++ std中使用getline()find_first_of(),以及在C中使用strtok()等不同方法实现的最佳实践。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接