在leedcode上刷题遇见了一个问题,错误的使用字符串函数find_last_of(),随查阅资料整理了这个三个函数的使用。
find()函数:
语法:
size_type find( const basic_string &str, size_type index ); size_type find( const char *str, size_type index ); size_type find( const char *str, size_type index, size_type length ); size_type find( char ch, size_type index ); |
- 返回str在字符串中第一次出现的位置(从index开始查找)。如果没找到则返回string::npos,
- 返回str在字符串中第一次出现的位置(从index开始查找,长度为length)。如果没找到就返回string::npos,
- 返回字符ch在字符串中第一次出现的位置(从index开始查找)。如果没找到就返回string::npos
例如,
string s("Hallow world balabala!"); unsigned int loc = s.find( "wo", 0 ); if( loc != string::npos ) cout << "Position:" << loc << endl; else cout << "Didn't find" << endl;
find_first_of()函数:
语法:
size_type find_first_of( const basic_string &str, size_type index = 0 ); size_type find_first_of( const char *str, size_type index = 0 ); size_type find_first_of( const char *str, size_type index, size_type num ); size_type find_first_of( char ch, size_type index = 0 ); |
- 查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。从index向后开始,如果没找到就返回string::npos
- 查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。从index向后开始,最多搜索num个字符。如果没找到就返回string::npos,
- 查找在字符串中第一个与ch匹配的字符,返回它的位置。从index向后开始。
find_last_of
语法:
size_type find_last_of( const basic_string &str, size_type index = npos ); size_type find_last_of( const char *str, size_type index = npos ); size_type find_last_of( const char *str, size_type index, size_type num ); size_type find_last_of( char ch, size_type index = npos ); |
- 在字符串中查找最后一个与str中的某个字符匹配的字符,返回它的位置。从index开始向前搜索,如果没找到就返回string::npos
- 在字符串中查找最后一个与str中的某个字符匹配的字符,返回它的位置。从index开始向前搜索,最多搜索num个字符。如果没找到就返回string::npos
- 在字符串中查找最后一个与ch匹配的字符,返回它的位置。从index开始向前搜索。如果没找到就返回string::npos
在使用过程,当不设置搜索位置时,find()、find_first_of()默认从字符串0号位置搜索,find_last_of()默认从字符串最后一个字符位置查找。
例如:
我们从字符串中查找空字符出现的位置:
// main() 函数中: string s("Hellow world abc!"); unsigned int loc1 = s.find(' ',0); if (loc1 != string::npos && loc2 != string::npos && loc3 != string::npos)
position of ' ':6 //说明: 三个函数分别从0号位置,3号位置,和字符串最后一个位置开始查找,前两个从前往后查找,找到第一个空格,就返回其位置,最后一个从后往前查找,也是找到第一空格,就返回其位置。 |
参考博客: