Nov 17, 2012 at 6:50pm UTC
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 Nov 17, 2012 at 6:51pm UTC
Nov 17, 2012 at 7:49pm UTC
@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 :(
Nov 17, 2012 at 11:29pm UTC
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 Nov 18, 2012 at 3:10pm UTC