C++string中find,find_first_of和find_last_of的用法

1. size_t find (const string& str, size_t pos = 0)

str.find(str1)

说明:从pos(默认是是0,即从头开始查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的起始索引位置;如果没有找到则返回string::npos
参考:find函数:http://www.cplusplus.com/reference/string/string/find/

2. size_t find_first_of (const string& str, size_t pos = 0)

str.find_first_of(str1)

说明:从pos(默认是是0,即从头开始查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的起始索引位置;如果没有找到则返回string::npos
参考:find_first_of函数:http://www.cplusplus.com/reference/string/string/find_first_of/

3.size_t find_last_of (const string& str, size_t pos = npos)

str.find_last_of(str1)

说明:从npos(默认是字符串最后一个,即从后向前查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的最后一个字符的索引位置;如果没有找到则返回string::npos
参考: find_last_of函数http://www.cplusplus.com/reference/string/string/find_last_of/

举例如下:

#include<iostream>          
using namespace std;        
                            
int main(void)              
{                           
    string s = "一蓑烟雨任平生。";
    int len = s.size();     
    int count = s.size() / string("一").size();
    cout << "len = " << len << ", count = " << count << endl;
    cout << "find:平: pos = " << s.find("平") << endl;
    cout << "find_first_of:平: pos = " << s.find_first_of("平") << endl;
    cout << "find_last_of:平: pos = " << s.find_last_of("平") << endl;
    int pos = s.find("平", 9);                                                                                                                          
    cout << "pos:" << pos << endl;
    cout << "。: pos = " << s.find("。") << endl;
    cout << "。: pos = " << s.find_last_of("。") << endl;
    return 0;               
} 

结果:

len = 24, count = 8
find:平: pos = 15
find_first_of:平: pos = 15
find_last_of:平: pos = 17
pos:15
。: pos = 21
。: pos = 23
383281-20190701231745309-1202579685.png

总结:

C++中一个中文字符(包括汉字和中文符号)在字符串中的长度是3。在一个字符
串中查找中文字符的时候最好不要用find_last_of,因为用find_last_of返回的
是这个中文字符串的最后一个pos,而不是第一个,极容易出错。如上述例子如果
判断一句话是否是以句号结尾,如果用find_last_of进行查找会得到23而一个句
号的长度是3,加起来会大于整个字符串的长度,主要原因还是容易忘记他是子
串的最后一个pos,如果用find或者find_first_of,出错概率较低。

转载于:https://www.cnblogs.com/zh20130424/p/11099932.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值