函数std::string::find,rfind,find_first_of,find_last_of,find_first_not_of,find_last_not_of的基本使用

简概:

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

参考:

1.std::string中 find,rfind,find_first_of,find_last_of, find_first_not_of,find_last_not_of等函数的介绍和使用_std::string find-CSDN博客

2.size_t 数据类型_size-t-CSDN博客 

3.size_t数据类型的意义_sizet范围-CSDN博客 

4.彻底搞懂C++中string::npos-CSDN博客 

5.C语言中的size_t和size_type比较_size type-CSDN博客 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值