0

可能重复:
在 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
4

2 回答 2

1

如果您不想求助于其他库(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;
}
于 2013-01-13T18:37:09.870 回答
0

您可以找到逗号的索引并将它们存储在一个向量中,然后使用 string::substr (http://www.cplusplus.com/reference/string/string/substr/) 来获取这些索引之间的子字符串。

于 2013-01-13T18:29:51.940 回答