需要将字符串拆分为带分隔符的向量

时间:2016-11-20 00:05:00

标签: c++ string vector

以下代码应该使用函数拆分带分隔符的字符串。

给出以下函数声明:

vector<string> split(string target, string delimiter);

我需要实现该函数,以便它返回target中由字符串delimiter分隔的子字符串向量。例如:

split("10,20,30", ",")

应返回带有“10”,“20”和“30”字符串的vector。同样,

split("do re mi fa so la ti do", " ")

应该返回vector字符串“do”,“re”,“mi”,“fa”,“so”,“la”,“ti”和“do”。

我的代码只输出vector的第一个元素。我没有看到函数实现有什么问题。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> split(string, string);

int main()
{
    vector<string> v;
    string target;
    string delim;
    split(target, delim);
    v = split(target, delim);
    for (unsigned long i = 0; i < v.size(); i++)
        cout << v[i] << " ";
}

vector<string> split(string target, string delim)
{
    cout << "Enter string: "<< endl;
    getline(cin, target);
    cout << "Enter delimiter:" << endl;
    getline(cin, delim);
    vector<string> v;
    size_t x = target.find(delim);
    while (x!= string::npos) {
        v.push_back(target.substr(0,x));
        target = target.substr(x);
        x = target.find(delim);
    }
    return v;
}

1 个答案:

答案 0 :(得分:0)

尝试更像这样的东西:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> split(string, string);

int main()
{
    vector<string> v;
    string target;
    string delim;

    cout << "Enter string: "<< endl;
    getline(cin, target);
    cout << "Enter delimiter:" << endl;
    getline(cin, delim);

    v = split(target, delim);
    for (unsigned long i = 0; i < v.size(); i++)
        cout << v[i] << " ";
}

vector<string> split(string target, string delim)
{
    vector<string> v;
    if (!target.empty()) {
        string::size_type start = 0;
        do {
            size_t x = target.find(start, delim);
            if (x == string::npos)
                break;

            v.push_back(target.substr(start, x-start));
            start += delim.size();
        }
        while (true);

        v.push_back(target.substr(start));            
    }
    return v;
}