how to check if a string starts with a certain string?

if i want to see if

1
2
string question;
      cin >> question;


question starts with something like

"why are you"

How do i do?

Also i'm not searching for finding a string anywhere in the string, just searching for the certain string in the beginning of the string ;)
Well, you can either

#1 find the substring (string::find) and, if it's there, check that it's at the beginning of the string

#2 chop off the beginning of the string (string::substr) and then compare it against the expected value (== or string::compare)

Andy
Last edited on
@andywastken
I don't know how to chop off the beginning of the string or how to check that it's at the beginning of the string :(
Have you read up about the methods I mentioned?

From

string::find
http://www.cplusplus.com/reference/string/string/find/

Return Value
The position of the first occurrence in the string of the searched content.
If the content is not found, the member value npos is returned.


I hope #1 is now clear? If not, code a little fragment to test out how it works.

And

string::substr
http://www.cplusplus.com/reference/string/string/substr/

should anwer #2
@andywestken
Thanks, finally got it working the way i wanted :)
1
2
3
4
5
6
7
8
9
    string question;
    cout << "Write smt" << endl;
    getline( cin, question );
   string questionWord = "who are";
  int askingWordLength = questionWord.length();
  string askingSentence = question.substr(0,askingWordLength);
   if(question.find(askingSentence) !=string::npos && askingSentence == questionWord){
      cout << "found " << askingSentence << endl;
   }

probably a bad way, but it worked ;)
Cool!

And it's not a bad way. But you are doing the test kind of both ways at once...

In reverse order:

#2 using substr (but not find)

(this is more or less the same as your code -- it's just missing the unnecessary find)

1
2
3
4
5
6
7
8
9
10
11
12
13
    string question;
    cout << "Write smt" << endl;
    getline( cin, question );

    string questionWord = "who are";

    // get a substring as long as the question
    string askingSentence = question.substr(0, questionWord.length());

    // no need for find
    if(askingSentence == questionWord) {
        cout << "found " << questionWord << endl;
    }


#1 using find (but not substr)

1
2
3
4
5
6
7
8
9
10
    string question;
    cout << "Write smt" << endl;
    getline( cin, question );

    string questionWord = "who are";

    // no need for substr (if we find the substring at position 0...)
    if(0 == question.find(questionWord)) {
        cout << "found " << questionWord << endl;
    }


Andy

PS I changed the code in #2 to o/p questionWord rather askingSentence so it was consistent with #1
Last edited on
Topic archived. No new replies allowed.