C++ find_first_not_of() 和 find_first_of() 和 find()

find_first_not_of()函数

查找当前string与指定的字符串中任意一个字符都不相符的字符,并返回该字符在字符串中第一次出现的位置。

size_t find_first_not_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_not_of ( const char* str, size_t pos, size_t n ) const;
size_t find_first_not_of ( const char* str, size_t pos = 0 ) const;
size_t find_first_not_of ( char ch, size_t pos = 0 ) const;
  • 在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops
  • 在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从pos开始,最多查找n个字符。如果没找到就返回string::nops
  • 在字符串中查找第一个与ch不匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops

注:string::npos 表示string类中各种成员函数失败时返回的值,其值为-1。

find_first_of()函数

搜索字符串中属于任意一个str、s或c的字符,并返回字符串中第一个出现的位置。

size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char ch, size_t pos = 0 ) const;
  • 在字符串中查找第一个与str中的字符相匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops
  • 在字符串中查找第一个与str中的字符相匹配的字符,返回它的位置。搜索从pos开始,最多查找n个字符。如果没找到就返回string::nops
  • 在字符串中查找第一个与ch不匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops

注意:以上这两个方法都是查找当前string与指定的字符串中任意一个字符都不相符的字符的位置地址,而不是返回的是与指定的字符串完全匹配的字符串的首地址,如果若要匹配整个字符串,请使用find()。

应用Demo

#include <iostream>
#include <string>
using namespace std;
void find_first_not_of_test(void)
{
    string str="0123456789abcdef";
    int index01=str.find_first_not_of("013");
    cout << index01 << endl;
    int index02=str.find_first_not_of("0123456789abcdef");
    cout << index02 << endl;
}
void find_first_of_test(void)
{
    string str="0123456789abcdef";
    int index=str.find_first_of("456");
    cout << index << endl;
    int index02=str.find_first_of("zx2");
    cout << index02 << endl;
}
void find_test(void)
{
    string str="0123456789abcdef";
    int index=str.find("abc");
    cout << index << endl;
    int index02=str.find("xyz");
    cout << index02 << endl;
}
int main() {
    std::cout << "find_first_not_of_test" << std::endl;
    find_first_not_of_test();
    std::cout << "find_first_of_test" << std::endl;
    find_first_of_test();
    std::cout << "find_test" << std::endl;
    find_test();
    return 0;
}

运行如下:

find_first_not_of_test
2
-1
find_first_of_test
4
2
find_test
10
-1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值