Split string by a character?

user2705775 picture user2705775 · Dec 24, 2013 · Viewed 78.3k times · Source

How can I split a string such as "102:330:3133:76531:451:000:12:44412 by the ":" character, and put all of the numbers into an int array (number sequence will always be 8 elements long)? Preferably without using an external library such as boost.

Also, I'm wondering how I can remove unneeded characters from the string before it's processed such as "$" and "#"?

Answer

herohuyongtao picture herohuyongtao · Dec 24, 2013

stringstream can do all these.

  1. 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}
    
  2. Remove unneeded characters from the string before it's processed such as $ and #: just as the way handling : in the above.

PS: The above solution works only for strings that don't contain spaces. To handle strings with spaces, please refer to here based on std::string::find() and std::string::substr().