Saturday, 15 February 2014

C++: string.find finds a char in a string only if its on pos1 -



C++: string.find finds a char in a string only if its on pos1 -

i want find char (expected_char) in string (word) by

if (word.find(expected_char)==true) { cout << "you got one! it's on pos" << word.find(expected_char); } else { ... }

if string e.g. "abcd" , search "c" else executed; if search "b" if statement executed.

the homecoming type of std::string::find() unsigned type std::string::size_type, , returns either std::string::npos (which maximum value std::string::size_type can represent) if character not found, or first index of found character in string.

now comparing result of std::string::find() true, results in integral promotion of boolean value true integral value 1. thus, status satisfied if , if character expected_char found in position 1 (i.e. when sec character in string).

if want check whether character expected_char in string word, use

if (word.find(expected_char) != std::string::npos) { ... }

c++

No comments:

Post a Comment