Thursday, July 9, 2009

How to break up a string into multiple strings in C++?

I need to know to break up a string (or character array) into multiple strings in C++ based on spaces (it must be able to handle multiple spaces).





So, for example, if I have the string "aardvark cat dog person",


I need to get four different strings of "aardvark", "cat", "dog", "person".





How do I do this?

How to break up a string into multiple strings in C++?
The C std library (C++ is a superset of C) includes the strtok method which allows you to specify a token (in your case space) which will then split the input string into an array of strings broken at the token you specify.





Google string token function in C and look at examples. It's a little confusing to understand at first but if you copy an example, should be easy to implement in a few lines of code. The previous answer is about 20 lines more than you really need.
Reply:use a 2d array then !!!!!!


so simple





here u go








while(i%26lt;l)


{


if((ar[i]==' ')%26amp;%26amp;(i%26lt;l))


{


while((ar[i]==' ')%26amp;%26amp;(i%26lt;l))


{


i++; //skipping spaces


}


}





else if((ar[i]!=' ')%26amp;%26amp;(i%26lt;l))


{


while((ar[i]!=' ')%26amp;%26amp;(i%26lt;l))


{


a[r][j]=ar[i];


i++;


j++;//column of a[],the 2d array in which we are storing the


//words


}





r++;


a[r][j]= '\0' \\for null character,otherwise it will show u junk


\\values while printing


}








and then u print the 2d array,enjoy!


see the logic is the words get separated in different rows


so u can use them now for watever problem.......like sorting them alphabetically,printing them in orders of length,etc





any other problems just add me to ur answers profile

blazing star

No comments:

Post a Comment