So let's say that I have a string:
|
string name = "Dynamic_Squid"
|
How do I separate that string into two parts?
So in this case, I separated the string based on the "_" character, but it can be any character. How do I do this? Thanks.
Last edited on
Last edited on
here is a better version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void split(const string &str, const char delimiter, vector<string> &result)
{
string word;
for (size_t i = 0; i < str.length(); ++i)
{
if (str[i] == delimiter)
{
result.push_back(word);
word = "";
}
else
word += str[i];
}
if (str.size())
result.push_back(word);
}
int main()
{
string name = "Hello_World";
vector<string> result;
split(name, '_', result);
for (string &s : result)
cout << s << endl;
}
|
Last edited on
Last edited on
@mbozzi Very elegant solution. I totally forgot that you can iterate over regular expressions
Last edited on