0

Frequently, you may need to isolate words in a phrase. In this example, we'll use substr to carry out this task.

string phrase = "Now is the oppurtunity to claim money";
string word;
int i, space;
phrase+=" ";//add space to end of phrase
while(phrase.length()>0)
{
space = phrase.find();//find position of the first space in phrase
word = phrase.substr(0,space);
//process word here and then go to next word
cout<<word<<endl;
phrase = phrase.substr(space+1);//create new phrase with first word chopped off
}//end while phrase
3
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by zandiago
0

Another way to get the substrings of the given string with spaces as delimiters can be

#include<string>
#include<sstream>
using namespace std;

string givenString="This is the string to be split";
stringstream s;
string temp;
s<<givenString;
while(s>>temp)
cout<<temp<<endl;
0

Thank you guys for your comment, will be posting a few more within the next week or so.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.