Inputing variable into string.find

Jan 28, 2010 at 1:20pm
Hey guys, could i check with something

What i would like to do is to be able to input a number and using that number as the index , it will start finding where a certain line is (in this case yht) from there. for example

1
2
3
4
5
6
7
8
9
int main ()
{
string s("abcdefghijleeeeeeeyhtpr") ;


string::size_type loc2 = s.find( "yht" , 0 )  ;


cout << loc2 << endl ;


the input will be 18 , as it starts counting from the start of the string. What i would like to know is, am i able to set a variable in the find syntax? instead of putting 0 , can i declare a variable and then can the sting.find() read it?

So , if i were to input in 3 , how can i declare this and then put it into the find statement? Hope for some help. thanks
Jan 28, 2010 at 1:27pm
The index is an int. Have you tried it? off the top of my head and knowing how languages work I would say "it should work", but then I have not tried myself.

EDIT: I assume you mean something like this ?

1
2
3
4
5
6
7
8
9
int main ()
{
   string s("abcdefghijleeeeeeeyhtpr") ;
   int position = 5;   // little hint :)

   string::size_type loc2 = s.find( "yht" , position )  ;
   cout << loc2 << endl ;

   ...


The question maybe you should be asking is: what does the index do?
and the answer can be found in the API:

http://cplusplus.com/reference/string/string/find/
Last edited on Jan 28, 2010 at 1:36pm
Jan 28, 2010 at 2:05pm
Hey , thanks for the tip. i tried it that method at first but based on the results , i thought it did not work.

The reason was i thought if i stated the index on where to start searching from, the result it gives me will be based on where it starts off.

But according to some help i got, it does start reading from the index i set it to be, but the output it gives me will be based from the start of the line.

for example, if the index is 3 , it will start reading at c. but the output given to me will still be 18 . which is the start of the line right?

Jan 28, 2010 at 3:46pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

int main()
{
    std::string str("abcde");
    size_t pos = 0;
    
    // start from 1
    pos = str.find('e', 1);
    std::cout << pos << '\n';
    
    // start from 0, beginning
    pos = str.find('e', 0);
    std::cout << pos;
    
    std::cin.get();
    return 0;
}


So the line: pos = str.find('e', 1); yields the same result as pos = str.find('e', 1); except in the first line the position you started from is added on.
Topic archived. No new replies allowed.