C++ string查找子串位置

find_first_of()find()strstr()

find_first_of()查找的是子串中任意字符首次出现的位置。而find()是查找子串整体出现的位置。


    string str1 = "ahedhello111";
    string str2 = "hello";
    string str3 = "helle";
    
    cout << "find first of str2: " << str1.find_first_of(str2) << endl; //返回1
    cout << "find first of str3: " << str1.find_first_of(str3) << endl; //返回1
    
    cout << "find str2: " << str1.find(str2) << endl; //返回即子字符串索引4  
    cout << "find str3: " << str1.find(str3) << endl; //查找失败,返回-1  
        

strstr()也是查找子串整体,与find()不同的是处理类型不同。strstr()处理的是char*

  • 函数原型:char *strstr(const char *str1, const char *str2);
  • 返回值:成功找到,返回在父串中第一次出现的位置的 char *指针;若未找到,即不存在这样的子串,返回 NULL。

 char a[] = "ahedhello111";
 char b[] = "dda";
 char *rel = strstr(a, b); //首次出现地址,strstr保存的是ddabc
    if (rel != NULL)
        j = rel -a;         //根据返回子字符串匹配结果输出索引位


参考:
[1]C/C++库函数strstr和find实现子字符串查找
[2]【C/C++】关于strstr函数和c_str()函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MOLWH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值