the ques ==> Write a series of assignment statements that find the first three positions of the string"and" in a string variable sentence.The positions should be stored in int variables called first , second and third .
I've solved it .But I want to check
if my answer is right ?
...........................................
#include<iostream>
#include<string>
using namespace std;
first = sentence.find("a");
second = sentence.find("n");
third = sentence.find("d");
cout << first <<endl << second << endl << third << endl;
return 0;
Then, do I have to write "and" in each position instead of characters ?
But the values will be the same !
Yes, but you can use the last found offset (+3 as the size of "and" ist 3) to find the next (second) "and". Then take the second offset to find the third.
Note that the offset may be npos. Then no other find() should be done.
string sentence = "1 and 2 and 3 and 4";
string::size_type first;
string::size_type second;
string::size_type third;
first = sentence.find("and");
if(first != string::npos)
{
cout << "found the first 'and' at position " << first << endl;
second = sentence.find("and", first + 3);
if(second != string::npos)
...
}
else
{
cout << "There's no first 'and'" << endl;
second = string::npos;
}