String 查找函数c++

(一)String 类提供了六种查找函数 

(1)find    rfind

例一

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str="01234567890000";
    int a;
    a=str.find("0");
    cout<<a<<endl;//返回0 
    a=str.find("123");
    cout<<a<<endl;//返回1 
    a=str.find("456");
    cout<<a<<endl;//返回4 
    system("Pause");
    return 0;
}
查到第一个就返回,不管以后有几个,字符串就返回第一个字符的位置,从0开始数,操作全都返回 string::size_type 类型的值,以下标形式标记查找匹配所发生的位置;或者返回一个名为 string::npos 的特殊值,说明查找没有匹配。 npos = -1代表字符串索引号的末尾一个。或者表示无效索引号
hyhjTag.find("|" + acitveTag + "|") != string::npos 说明如果hyhjTag等于activeTag   
rfind同理只不过是反向查找

(二)find_first_of  	find_last_of  	 find_first_not_of()	find_last_not_of()


 
 
find_first_of(), find_last_of(), find_first_not_of(), find_last_not_of()
作用是查找   字符串中  任一个字符 满足的查找条件
string snake1("cobra");
int where = snake1.find_first_of("hark");
返回3  因为 "hark"中 各一个字符 在 snake1--cobra 中第一次出现的是  字符'r'(3为 cobra 中'r'的索引)
同理:
int where = snake1.find_last_of("hark");
返回4  因为 "hark"中 各一个字符 在 snake1--cobra 中最后一次出现的是  字符'a'(3为 cobra 中'r'的索引)
例二
#include<iostream> #include<string> using namespace std; void  main() { string s("Study hard and make progress every day!every day!!"); int loc; loc=s.rfind("make",10); cout<<"The word make is at index "<<loc<<endl; loc=s.rfind("make",40); cout<<"the word is at index"<<loc<<endl; loc=s.find_first_of("day"); cout<<"the word day(first) is at index"<<loc<<endl; } 输出结果:The word make is at index -1 the word is at index15 the word day(first) is at index3
;//从pos开始从后向前查找字符c在当前串中的位置int rfind(const char *s, int pos = npos) const; int rfind(const string &s,int pos = npos) const;   第一个从 第10个符号开始,向前找 "make" ,因为没有,所以直接返回 -1 第二个从 第40个符号开始, 向前找"make" ,返回 15 第三个从 整个字符串的最想向前找 "day",所以返回 3

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值