基于特定分隔符拆分字符串的最有效的c++方法是什么?类似于python中的split方法

What is the most efficient C++ method to split a string based on a particular delimiter similar to split method in python?

本文关键字:方法 是什么 python split 中的 类似于 有效 分隔符 于特定 拆分 字符串      更新时间:2023-10-16
getline(cin,s);
istringstream iss(s);
do
{
    string sub;
    iss>>sub;
    q.insert(sub);
 }while(iss);

当question想要我在空间的基础上进行分割时,我使用了这种技术,所以谁能告诉我当有一个特定的分隔符,如';'或':'时,如何分割?

有人告诉我关于strtok函数,但我不能得到它的用法,所以如果有人能帮助,那就太好了。

首先,不要使用strtok。。

在标准库中并没有这样的函数。我使用如下:

std::vector<std::string>
split( std::string const& original, char separator )
{
    std::vector<std::string> results;
    std::string::const_iterator start = original.begin();
    std::string::const_iterator end = original.end();
    std::string::const_iterator next = std::find( start, end, separator );
    while ( next != end ) {
        results.push_back( std::string( start, next ) );
        start = next + 1;
        next = std::find( start, end, separator );
    }
    results.push_back( std::string( start, next ) );
    return results;
}

我相信Boost有很多这样的函数。(我实现我的大部分都是在Boost出现之前。)