Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a string by space? How do i know the index no of the word i currently am on in the string?

Tags:

c++

string

This code that i have written loops through a string char by char. What i want is to loop through a string word by word. Here is my code.

string a; // already declared
   // c is string array
for (i=0;i<b;i++) {
    if (strcmp (c[i],a[i]) == 0 ) {
      // do something
       }
     }
like image 526
amian Avatar asked Nov 10 '13 07:11

amian


1 Answers

You can use string-streams:

string a = "hello   my name    is    joe";
stringstream s(a);
string word;
// vector<string> c = ... ;

for (int i = 0; s >> word; i++)
{
    if (word == c[i])
    {
        // do something
    }
}

If you want to have the ability to go front and back in words, you should store them in an array, so this second code is useful for that:

string a = "hello   my name    is    joe";
vector<string> c = {"hello","my","name","is","joe"};
string word;
vector<string> words;

for (stringstream s(a); s >> word; )
    words.push_back(word);

for (int i=0; i<words.size(); i++)
{
    if (words[i] == c[i])
    {
        // do something
    }
}
like image 93
masoud Avatar answered Nov 14 '22 22:11

masoud