split string (unknown len)

hello there.

I manage to split this str = "abc,def,123"
to s1 = "abc", s2 = "def", s3 = "123" with this piece of code using find and substr.
1
2
3
4
5
6
7
8
9
10
11
string str, s1, s2, s3;
getline(cin, str);
unsigned pos1 = str.find(",");
s1 = str.substr(0, pos1);
str = str.substr(pos1 + 1);
pos1 = str.find(",");
s2 = str.substr(0, pos1);
s3 = str.substr(pos1 + 1);
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;


But what should I do if the len of the string is unknown ?
For example, str = "abc,def,123,ghi,jkl,456,mno" and so on...

Any help will be appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<sstream>
#include<vector>
#include<string>

int main ()
{
    std::string str = "abc,def,123,ghi,jkl,456,mno";

    std::stringstream to_split(str);
    std::vector<std::string> strings;
    std::string temp;
    while( getline(to_split, temp, ',') )
        strings.push_back(temp);

    for(auto x: strings)
        std::cout << x << std::endl;
}

Output:
abc
def
123
ghi
jkl
456
mno
Last edited on
much appreciated, mate!
Thank you very much.

But I want to do it without #include<sstream> and without #include<vector>

using only #include<string> #include<iostream>

Sorry for the ignorance
Without vectors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<sstream>
#include<string>

int main ()
{
    std::string str = "abc,def,123,ghi,jkl,456,mno";

    std::string strings[100];
    std::stringstream to_split(str);
    std::string temp;
    int i = 0;
    while( getline(to_split, temp, ',') )
        strings[i++] = temp;
        
    for(int x = 0; x < i; ++x)
        std::cout << strings[x] << std::endl;
}

Stringstreams was created exactly for these situations. you can take c-string with str.c_str(), then split it with strtok() function from <cstring>
http://cplusplus.com/reference/cstring/strtok/
You can use find() and substr() by putting it inside loop like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<string>

int main ()
{
    std::string str = "abc,def,123,ghi,jkl,456,mno";

    std::string strings[100];
    unsigned string_num = 0;
    unsigned position;
    do {
        position = str.find(",");
        strings[string_num++] = str.substr(0, position);
        str = str.substr(position + 1);
    } while(position != str.npos);

    for(int x = 0; x < string_num; ++x)
        std::cout << strings[x] << std::endl;
}

But is s;ow and is reinventing a wheel. Square wheel, I say.
Thank you very much!!

What an amazing person.

Thanks !!
Topic archived. No new replies allowed.