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

find: 查找子串在字符串中第一次出现的位置,必须匹配完整子串。

string  s = "Hello, world!";
int npos = s.find("world");
std::cout << npos<<"\n";

rfind : 查找子串在字符串中最后一次出现的位置,必须匹配完整子串。

string s = "Hello, world!";
int npos1 = s.rfind("world");
std::cout << npos1 << "\n";

find_first_of : 查找子串中任意字符在字符串中第一次出现的位置,任意子串中字符。

string s = "Hello, world!";
int npos2 = s.find_first_of("Hello World!");
std::cout << npos2 << "\n";

find_last_of : 查找子串中任意字符在字符串中最后一次出现的位置,任意子串中字符。

string s = "Hello, world!";
int npos3 = s.find_last_of("Hello World!");
std::cout << npos3 << "\n";

find_first_not_of : 查找字符串中第一个不包含在待查找字符串中的字符的位置,也是任意字符。

string s = "Hello, world!";
int npos4 = s.find_first_not_of("HeLo");
std::cout << npos4 << "\n";

find_last_not_of : 查找字符串中最后一个不属于待查找字符串中的字符的位置,也是任意字符

string s = "Hello, world!";
int npos5 = s.find_last_not_of("HeLo");
std::cout << npos5 << "\n";

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
除了 `find_first_of`,`std::string` 类还有一些其他的查找函数,它们的作用都是在字符串查找指定字符或字符集的位置。下面是几个常用的查找函数及其功能: 1. `find(char ch, size_t pos = 0) const`:在字符串查找字符 `ch` 的位置,从 `pos` 位置开始查找,默认值为 0。 ```cpp std::string s = "hello, world!"; size_t pos = s.find('o'); // 返回 4 ``` 2. `rfind(char ch, size_t pos = npos) const`:在字符串查找字符 `ch` 的位置,从 `pos` 位置往前查找,`npos` 表示从字符串的末尾开始查找。 ```cpp std::string s = "hello, world!"; size_t pos = s.rfind('o'); // 返回 8 ``` 3. `find_first_of(const char* str, size_t pos = 0) const`:在字符串查找第一个匹配指定字符集任意一个字符的位置。 ```cpp std::string s = "hello, world!"; size_t pos = s.find_first_of("ow"); // 返回 4 ``` 4. `find_last_of(const char* str, size_t pos = npos) const`:在字符串查找最后一个匹配指定字符集任意一个字符的位置。 ```cpp std::string s = "hello, world!"; size_t pos = s.find_last_of("ow"); // 返回 9 ``` 5. `find_first_not_of(const char* str, size_t pos = 0) const`:在字符串查找第一个不匹配指定字符集任意一个字符的位置。 ```cpp std::string s = "hello, world!"; size_t pos = s.find_first_not_of("helo, "); // 返回 5 ``` 6. `find_last_not_of(const char* str, size_t pos = npos) const`:在字符串查找最后一个不匹配指定字符集任意一个字符的位置。 ```cpp std::string s = "hello, world!"; size_t pos = s.find_last_not_of("dlrow!"); // 返回 10 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值