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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With