c++ Split string by a character?

This question already has an answer here:

  • The most elegant way to iterate the words of a string [closed] 74 answers

  • stringstream can do all these.

  • Split a string and store into int array:

    string str = "102:330:3133:76531:451:000:12:44412";
    std::replace(str.begin(), str.end(), ':', ' ');  // replace ':' by ' '
    
    vector<int> array;
    stringstream ss(str);
    int temp;
    while (ss >> temp)
        array.push_back(temp); // done! now array={102,330,3133,76531,451,000,12,44412}
    
  • Remove unneeded characters from the string before it's processed such as $ and # : just as the way handling : in the above.


  • The standard way in C is using strtok like others have answered. However strtok is not C++ -like and also unsafe. The standard way in C++ is using std::istringstream

    std::istringstream iss(str);
    char c; // dummy character for the colon
    int a[8];
    iss >> a[0];
    for (int i = 1; i < 8; i++)
        iss >> c >> a[i];
    

    In case the input always has a fixed number of tokens like that, sscanf may be another simple solution

    std::sscanf(str, "%d:%d:%d:%d:%d:%d:%d:%d", &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8);
    

    I had to write some code like this before and found a question on Stack Overflow for splitting a string by delimiter. Here's the original question: link.

    You could use this with std::stoi for building the vector.

    std::vector<int> split(const std::string &s, char delim) {
        std::vector<int> elems;
        std::stringstream ss(s);
        std::string number;
        while(std::getline(ss, number, delim)) {
            elems.push_back(std::stoi(number));
        }
        return elems;
    }
    
    // use with:
    const std::string numbers("102:330:3133:76531:451:000:12:44412");
    std::vector<int> numbers = split(numbers, ':');
    

    Here is a working ideone sample.

    链接地址: http://www.djcxy.com/p/19572.html

    上一篇: 在C ++中分割字符串

    下一篇: c ++字符串拆分字符串?