C++, how do I compare strings? (not c-style)

Started by
13 comments, last by Telastyn 18 years, 9 months ago
Quote:Original post by darenking
OK, I can do it like this:

if ( line.find("hello") == 0 )

This checks to see if the string contains "hello" starting at the start of the string (position 0).

Works just fine, though I do wonder if there's a string method that checks to see if the string is exactly equal to 'hello'. The above would return 0 if the string is 'hello' but it will also return 0 if the string is 'hellogoodbye'.



if you want to check the first 2 chars in phrase then write this
string.substr(0,2) == "//"
Advertisement
Quote:Original post by Gink

if you want to check the first 2 chars in phrase then write this
string.substr(0,2) == "//"


The only problem with that method is your creating a temporary which is redundant.
what is redundant about it?
You might want to consider posting your code. == does work for C++ strings.

string val = "hello"if(val == "hello"){    return true;}else{     return false;}


The above example would return true.
I wouldn't be suprised if the string is being read in, and has some sort of trailing whitespace and/or newline.

This topic is closed to new replies.

Advertisement