4

可能重复:
如何在 C++ 中标记字符串?
在 C++ 中拆分字符串

请问在 C++ 中有没有类似 python.split(",") 的方法。

4

1 回答 1

0

从某些地方获得以下代码..可能会有所帮助

#define MAIN 1
#include <string>
#include <vector>
#include <iostream>
using namespace std;

class splitstring : public string {
    vector<string> flds;
public:
    splitstring(char *s) : string(s) { };
    vector<string>& split(char delim, int rep=0);
};

vector<string>& splitstring::split(char delim, int rep) {
    if (!flds.empty()) flds.clear();
    string work = data();
    string buf = "";
    int i = 0;
    while (i < work.length()) {
        if (work[i] != delim)
            buf += work[i];
        else if (rep == 1) {
            flds.push_back(buf);
            buf = "";
        } else if (buf.length() > 0) {
            flds.push_back(buf);
            buf = "";
        }
        i++;
    }
    if (!buf.empty())
        flds.push_back(buf);
    return flds;
}

#ifdef MAIN
main()
{
    splitstring s("Humpty Dumpty sat on a wall.   Humpty Dumpty had a great fall");
    cout << s << endl;

    vector<string> flds = s.split(' ');
    for (int k = 0; k < flds.size(); k++)
        cout << k << " => " << flds[k] << endl;

    cout << endl << "with repeated delimiters:" << endl;
    vector<string> flds2 = s.split(' ', 1);
    for (int k = 0; k < flds2.size(); k++)
        cout << k << " => " << flds2[k] << endl;
}
#endif

在提升:

vector<string> results;
boost::split(results, line, boost::is_any_of("@"));

在 STL 中:

template <typename E, typename C>
size_t split(std::basic_string<E> const& s, C &container,
        E const delimiter, bool keepBlankFields = true) {
    size_t n = 0;
    std::basic_string<E>::const_iterator it = s.begin(), end = s.end(), first;
    for (first = it; it != end; ++it) {
        if (delimiter == *it) {
            if (keepBlankFields || first != it) {
                container.push_back(std::basic_string<E > (first, it));
                ++n;
                first = it + 1;
            } else ++first;
        }
    }
    if (keepBlankFields || first != it) {
        container.push_back(std::basic_string<E > (first, it));
        ++n;
    }
    return n;
}
于 2013-01-19T12:47:39.803 回答