Another use of substr

zandiago 0 Tallied Votes 141 Views Share

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
munyu 0 Newbie Poster

an excellent tip and well commented

HackWizz 0 Junior Poster in Training

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;
zandiago 115 Nearly a Posting Maven Featured Poster

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.