简概:
find:字符串中找子串首次出现的地方(需完整子串)
rfind:字符串中找子串最后一次出现的地方(需完整子串)
find_first_of:字符串中找子串中字符首次出现的地方(子串中任意字符)
find_last_of:字符串中找子串中字符最后一次出现的地方(子串中任意字符)
find_first_not_of:字符串中没有找到子串中字符首次出现的地方(子串中任意字符)
find_last_not_of:字符串中没找到子串中字符最后一次出现的地方(子串中任意字符)
头文件:
#include <string>
using namespace std;
1.std::string::find
功能:在字符串s中寻找子串(字符或字符串)首次出现的地方(从左往右)
返回值:子串在字符串s中找到的第一个字符的位置【没找到会返回string::npos】
string s = "abcd Hello, word";
size_t pos5 = s.find('d'); //3 顺序从0开始 abc‘d’
size_t pos6 = s.find("Hello"); //5
2.std::string::rfind
功能:在字符串s中寻找子串(字符或字符串)最后一次出现的地方(从右往左)
返回值:子串在字符串s中找到的最后一个字符的位置
string s = "abcd Hello, word";
size_t pos11 = s.rfind('d'); //15 wor‘d’
3.std::string::find_first_of
功能:在字符串s中寻找子串(字符或字符串)中任意一个字符第一次出现的地方(从左往右)
返回值:子串中任意一个字符在字符串s中找到的第一个字符的位置
string s = "abcd Hello, word";
size_t pos7 = s.find_first_of("HeL"); //5 ‘H’ello
4.std::string::find_last_of
功能:在字符串s中寻找子串(字符或字符串)中任意一个字符最后一次出现的地方(从右往左)
返回值:子串中任意一个字符在字符串s中找到的最后一个字符的位置
string s = "abcd Hello, word";
size_t pos8 = s.find_last_of("HeL"); //6 H‘e’llo
5.std::string::find_first_not_of
功能:在字符串s中没有寻找子串(字符或字符串)中任意一个字符第一次出现的地方(从左往右)
返回值:子串中任意一个字符在字符串s中没有找到的第一个字符的位置
string s = "abcd Hello, word";
size_t pos9 = s.find_first_not_of("HeL"); //0 ‘a’bcd
6.std::string::find_last_not_of
功能:在字符串s中没有寻找子串(字符或字符串)中任意一个字符最后一次出现的地方(从右往左)
返回值:子串中任意一个字符在字符串s中没有找到的最后一个字符的位置
string s = "abcd Hello, word";
size_t pos10 = s.find_last_not_of("HeL"); //15 wor‘d’
7.std::string::npos
std::string中的一个常量静态成员值,作为一个返回值,没有找到任何匹配的字段(find,rfind,find_first_of,find_last_of,find_first_not_of,find_last_not_of,substr,erase等,这些函数返回值都是size_t类型)
string s = "abcd Hello, word";
BOOL bPos = s.find('g') == string::npos ? TRUE : FALSE; //1,not found
注:
(1)int:有符号整数类型
(2)size_t :无符号整数类型(正整数),表示对象大小,C中任何对象所能达到的最大长度,是unsigned int 和 unsigned long的别名,用于数组长度,内存分配和字符串等场景(适用于多平台,有可移植性)
(3)size_type:表示对象大小,是unsigned int 和 unsigned long的别名,用于容器类(vector,string)和算法等场景
string s = "abcd Hello, word";
int pos4 = s.find('d'); //3
size_t pos5 = s.find('d'); //3
string::size_type pos6 = s.find("Hello"); //5
参考: