.find() programming



hi,

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;

int main()
{

string sentence = "and";
string::size_type first;
string::size_type second;
string::size_type third;

first = sentence.find("a");
second = sentence.find("n");
third = sentence.find("d");
cout << first <<endl << second << endl << third << endl;
return 0;

}
...............................................

Ist like what they want in the question?! :/


I doubt it is. You're probably supposed to find the first three occurrences of "and" in the sentence, not the individual characters.
Ist like what they want in the question?! :/
No, I don't think so.

I think you should find the word "and" as whole and then based on that position find the next an so on.

Hint: find returns an offset. find also takes as a second parameter an offset (default is 0)
Then, do I have to write "and" in each position instead of characters ?
But the values will be the same !
..

Thuraya wrote:
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.
Last edited on
Ok, here's the example what I mean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}
coder777
you mean like this :

first = sentence.find("and")+3;
second = sentence.find("and")+2;
third = sentence.find("and")+1;

??
Thuraya wrote:
you mean like this :
No, read my previous post and especially look at line 10.

aha, Now I got it ^^

thanks.
Topic archived. No new replies allowed.