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 "#"?
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.
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()
.