std::string中 find,rfind,find_first_of,find_last_of, find_first_not_of,find_last_not_of等函数的介绍和使用

目录

每个函数的介绍与示例

例子

结果

结论

这些都是C++中string类的成员函数,用于在字符串中查找特定字符或子串。

每个函数的介绍与示例

1. find():此函数用于查找子串在字符串中首次出现的位置。如果找到,返回的位置是子串在原字符串中的开始位置。如果没有找到,返回string::npos。 

例如:

string s = "Hello, world!";  
size_t pos = s.find("world"); // pos == 7

 2. rfind():此函数用于查找子串在字符串中最后一次出现的位置。如果找到,返回的位置是子串在原字符串中的开始位置。如果没有找到,返回string::npos。

例如:

string s = "Hello, world!";  
size_t pos = s.rfind("world"); // pos == 7

 3. find_first_of():此函数用于查找字符串中第一个出现指定字符的位置。如果找到,返回的位置是字符在原字符串中的开始位置。如果没有找到,返回string::npos。

例如:

string s = "Hello, world!";  
size_t pos = s.find_first_of("Hello, world!"); // pos == 0

 4. find_last_of():此函数用于查找字符串中最后一个出现指定字符的位置。如果找到,返回的位置是字符在原字符串中的开始位置。如果没有找到,返回string::npos。

例如:

string s = "Hello, world!";  
size_t pos = s.find_last_of("Hello, world!"); // pos == 12

 5. find_first_not_of():此函数用于查找字符串中第一个不包含指定字符的位置。如果找到,返回的位置是字符在原字符串中的开始位置。如果没有找到,返回string::npos。

例如:

string s = "Hello, world!";  
size_t pos = s.find_first_not_of("HeLo"); // pos == 2

 6. find_last_not_of():此函数用于查找字符串中最后一个不包含指定字符的位置。如果找到,返回的位置是字符在原字符串中的开始位置。如果没有找到,返回string::npos。

例如:

string s = "Hello, world!";  
size_t pos = s.find_last_not_of("HeLo"); // pos == 12

注意:这些函数都是区分大小写的,如果你需要忽略大小写,可以在调用前使用std::transform函数将所有字符转化为大写或小写。

例子

    std::string s = "abc Hello, world! world world hello";
    std::cout << "find:" << s.find("world") << std::endl;
    std::cout << "rfind:" << s.rfind("world") << std::endl;
    std::cout << "find_first_of:" << s.find_first_of("Hello, worlld!") << std::endl;
    std::cout << "find_last_of:" << s.find_last_of("Hello, wohrld!") << std::endl; 

    string s1 = "Hello, world!";  
    std::cout << "find_first_not_of:" << s1.find_first_not_of("HeLo") << std::endl;
    std::cout << "find_last_not_of:" << s1.find_last_not_of("HeLo") << std::endl;

结果

find:11
rfind:24
find_first_of:3
find_last_of:34
find_first_not_of:2
find_last_not_of:12

结论

find: 查找子串在字符串中第一次出现的位置,必须匹配完整子串
rfind: 查找子串在字符串中最后一次出现的位置,必须匹配完整子串
find_first_of: 查找子串中任意字符在字符串中第一次出现的位置,任意子串中字符
find_last_of: 查找子串中任意字符在字符串中最后一次出现的位置,任意子串中字符
find_first_not_of: 查找字符串中第一个不包含在待查找字符串中的字符的位置,也是任意字符
find_last_not_of: 查找字符串中最后一个不属于待查找字符串中的字符的位置,也是任意字符
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

telllong

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

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

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

打赏作者

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

抵扣说明:

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

余额充值