split c++ string

Nov 15, 2013 at 2:07am
I have this string d ="3 J JD, K" and i want to split the string to individual string. I have this code which eliminates the comma but doesn't split the string into individual string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
#include <string>
#include <sstream>

using namespace std; 
int main()
{ 
   string str = "3   J     JD,K";
   stringstream ss(str);

   string token;

while (getline(ss,token, ','))
{
    cout<< token <<endl; 
}

 
   return 0;
}
 

Output of the code is
1
2
3   J   JD
k


but I want
1
2
3
4
3
J
JD
K

Also after I split the string is there any way to put the split string into individual string variables.
Last edited on Nov 15, 2013 at 3:17am
Nov 15, 2013 at 2:34am
Since your delimiter here is spaces, all you have to do is replace the comma with a space, then use a std::istringstream to extract each token into a new string.
Nov 15, 2013 at 2:55am
thanks for the reply. When i replace the comma with space then the output is
1
2
3
3 
J 
JD,K


I need the output to be
1
2
3
4
3 
J 
JD
K

Also can you give me an example for istringstream
Nov 15, 2013 at 3:07am
You also have to change the comma in the string to a space.
Nov 15, 2013 at 3:10am
i can't change the comma into a space because i am reading this string from a file then i want to split the string and take out the comma
Nov 15, 2013 at 4:03am
i can't change the comma into a space because i am reading this string from a file then i want to split the string and take out the comma


Read the string in from the file.
Remove the comma (by replacing it with a space) from the string you read in.
Split the string.
Last edited on Nov 15, 2013 at 4:03am
Nov 15, 2013 at 2:32pm
1
2
3
4
5
6
7
8
9
string str = "3   J     JD,K";
// replace the comma with an empty space
replace(str.begin(), str.end(), ',', ' ');
stringstream ss(str);
string token;

while (getline(ss, token, ' '))
{
//etc. etc. 
Nov 15, 2013 at 3:25pm
You should use strtok()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream> 
#include <string>
#include <string.h>

using namespace std; 

int main() {
   string str = "3   J     JD,K";
   char* pch = strtok(str, " ,");
   cout<<pch<<endl;
   while(pch != NULL) {
       pch = strtok(NULL," ,");
       cout<<pch<<endl;
   }
   return 0;
}
Nov 15, 2013 at 4:14pm
1
2
   string str = "3   J     JD,K";
   char* pch = strtok(str, " ,");


This will not work because strtok takes a char* as a parameter, and not a std::string. Mixing C string functions with std::string is generally a bad idea.
Last edited on Nov 15, 2013 at 4:14pm
Nov 15, 2013 at 5:38pm
Using strtok() is generally a bad idea.
Topic archived. No new replies allowed.