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

时间:2013-01-13 18:26:14

标签: c++ delimiter

  

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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