user2705775 user2705775 -4 years ago 76
C++ Question

c++ Split string by a character?

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 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 Source

stringstream can do all these.

  1. Split a string and store into int array:

    string str = "102:330:3133:76531:451:000:12:44412";
    for (int i=0; i<str.length(); i++)
    {
        if (str[i] == ':')
            str[i] = ' ';
    }
    
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download