string find的用法详解

/*
string 
        find()的使用  


#include<iostream>
#include<string>
using namespace std;

int main(){
    string st1=("babbabab");

    //从前面找a的位置

    cout<<st1.find('a')<<"   ";  cout<<"输出第一个a的下标  (从0开始) "<<endl;
    cout<<st1.find('a',0)<<"     ";cout<<"('a',x) 从x下标开始查询a的下标"<<endl;

    //从后面找a 的位置 
    cout<<st1.rfind('a',1)<<"     ";cout<<"从0 到 x 从后向前查找a 所在该串的位置"<<endl; 

    cout<<(st1.find('c',0)==-1)<<endl;  //该数字不存在 就满足条件 为真 1     两句均输出1,原因是计算机中-1和4294967295都表示为32个1(二进制)

    //st1.find("y",x); 该y可以是字符串 字符 string char型 均可 

    cout<<st1.find("bababa",0,4)<<endl; //6   第三个参数不得超过第一个参数 

    return 0;
}



find() 的实例 
#include<iostream>
#include<string>
using namespace std; 
int main(){
    string str("babccbabcaabcc");

    int num=0;

    size_t fi=str.find("abc",0); 

    while(fi!=str.npos){ //没有找到一个 需要找到的位置 
        cout<<fi<<" ";
        num++; //统计一共有几个下标 
        fi=str.find("abc",fi+1); //输出下一个下标 
    }
    if(0==num) cout<<"not find!";
    cout<<endl;
    return 0;
}



*/

// find_first_of() 的用法 

// 同样  find_last_of(str,x);  意思是从 x向前找 如果存在一个与str中相同的 则输出该下标 
// 

//这里不再演示 find_first_not_of() find_last_not_of()的用法了 其作用是
//如果该字符在str中没有出现就输出该下标 

#include<iostream>
#include<string>
using namespace std;

int main(){
    string str("babccbabcc");
    cout<<str.find('a',0);//1
    cout<<str.find_first_of('a',0)<<endl; //1 从0开始只要找到a 就输出该a的小标

    string str1("bvgjhikl");
    string str2("kghlj");
    cout<<str1.find_first_of(str2,0)<<endl; //从str1的第0个字符开始 过程就是 b在str2中是否存在 如果存在就直接输出该下标
    //在找v是否在str2中是否存在 存在就输出改下标

    cout<<str1.find_first_of("kghlj",0,20);//2 第三个参数超过 
  • 9
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值