STL中string的搜索操作

string类提供了6个不同的搜索函数。每个函数有4个重载版本。每个搜索操作都返回一个string::size_type值,表示匹配发生位置的值。如果搜索失败,则返回一个string::npos的static 成员。标准库将npos定义为一个const string::size_type 类型,并初始化为值-1。

(1)find()函数

    string name("AnnaBelle");
    auto pos1 = name.find("Anna");// pos1 = 0

搜索是大小写敏感的。
(2) find_first_of() 和 find_first_not_of()函数

string numbens("0123456789");
string name("r2d2");
auto pos2 = name.find_first_of(numbers);// pos2 = 1,即name中的第一个数字

string dept("03714p3");
auto pos3 = dept.find_first_not_of(numbers);
//pos3 = 5,即字符 'p'的下标

(3) find_last_of()

当然,也可以指定搜索的开始位置、

string::size_type pos = 0;
//每步循环查找name 中的下一个数
while((pos = name.find_first_of(numbers,pos) != string::npos){
    cout<<"found number at index: "<< pos<<" element is " <<
    name[pos] <<endl;
    ++pos;//移动到下一个字符
}

(4)逆向搜索 rfind() 从有往左搜索

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值