String trouble

Hello I'm having a problem figuring out a string method.
I have read about string::find and string::npos to figure out that npos is a static value that is returned when string::find doesn't find anything. My problem is that when string::find is used to search a string it misses out the first index of that string. how does comparing it to npos make it look at the first index of the string. below is an example of what I mean.

1
2
3
string string1="ABCDEFG";
if(string1.find('A'))
cout << "it worked";


This will not find it since A is at the start but when I use this

1
2
3
string string1="ABCDEFG";
if(string1.find('A')!=string::npos)
cout << "it worked";


It works for some reason.
Is it because string::find does actually find the 'A' but because it is the first index [0] it is disregarded or something????? completely baffled but thanks to any one that helps
as you should know - a test for true or false on zero will return false.

so if(string1.find('A')) will test false if the A is at position 0;

The second method of testing if(string1.find('A')!=string::npos)
is the correct way to make the test.
Last edited on
Member function find returns position of searched element if it is found. In your example

string1.find('A') returns position equal to 0, because 'A' is the first symbol of the string. 0 means that the symbol is found and its position in the string equal to 0.

So the condition of the if-statement will be false because a numeric expression evalauted to 0 is equivalent to false.

if(string1.find('A'))


Last edited on
OMFG I LOVE YOU TWO SERIOUSLY THIS HELPED SO MUCH lol
Topic archived. No new replies allowed.