c++ - 在 C++ 中拆分字符串需要帮助

标签 c++ delimiter

<分区>

Possible Duplicate:
Splitting a string in C++

我需要一个关于如何在不使用任何外部库的情况下获取一串文本并根据特定字符将其拆分的建议,在本例中为“,”

文本行是:

Amadeus,Drama,160 Mins.,1984,14.83
As Good As It Gets,Drama,139 Mins.,1998,11.3
Batman,Action,126 Mins.,1989,10.15
Billy Elliot,Drama,111 Mins.,2001,10.23
BR,SF,117,1982,11.98
Shadowlands,Drama,133 Mins.,1993,9.89
Shrek,Animation,93 Mins,2001,15.99
Snatch,Action,103 Mins,2001,20.67
The Lord of the Rings,Fantasy,178 Mins,2001,25.87

最佳答案

如果您不想求助于其他库(Boost.Tokenizer 是 IMO 的不错选择),这里有一些简单的代码:

#include <string>
#include <vector>

using namespace std;

vector<string> tokenize(string const& s, string const& separator)
{
    size_t start = 0;
    size_t pos = s.find(separator);

    vector<string> v;
    while (pos != string::npos)
    {
        string sub = s.substr(start, pos - start);
        v.push_back(sub);

        start = pos + 1;
        pos = s.find(separator, start);
    }

    string sub = s.substr(start, pos - start);
    v.push_back(sub);

    return v;
}

int main()
{
    string s = "asfa,adf,daf,c";
    vector<string> v = tokenize(s, ",");

    // Do what you want with v...

    return 0;
}

关于c++ - 在 C++ 中拆分字符串需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306689/

相关文章:

c++ - 在 Rcpp 函数中使用 Bool-Vector 进行子集化(Rcpp 初学者的问题...)

c++ - 将 OpenGL 渲染保存到图像文件

java - java中的分隔符

mysql - 未知列 '..' 加入 'field list'

hadoop - 无法在 hadoop mapreduce 中使用 KeyValueTextInputFormat 解析输入

c++ - boost multi_index_container 和内存碎片

c++ - 如何从 char 数组复制 wchar_t

c++ - 编译器忽略显式定义的 move 构造函数?

Java 扫描器定界符用法