std::string中的find_first_of()和find_last_of()函数

编程语言: c++/linux

在std::string中,有时需要找到一个string中最后一个或者第一个以某个特定的字符开始的位置或者下标,这时就需要使用find_first_of()和find_last_of()函数。

find_first_of() : 找到一个string中第一个以 某个 字符开始的位置

find_last_of() :找到一个string中最后一个以 某个 字符开始的位置

使用方式如下:

#include <iostream>
#include <string>

int main () {
  std::string str1 ("tvab33_v12");

  std::size_t pos_first = str1.find_first_of('v');
  std::cout << "pos_first=" << pos_first << std::endl;

  std::size_t pos_last = str1.find_last_of('v');
  std::cout << "pos_last=" << pos_last << std::endl;

  return 0;
}

结果:

 还有另外2个函数:

find_first_not_of("abc") : 找到string中第一个不是以字符'a'/'b'/'c'开始的字符的位置
find_last_not_of("abc") :  找到string中最后一个不是以字符'a'/'b'/'c'开始的字符的位置

// string::find_first_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main () {
  std::string str ("look for non-alphabetic characters...");

  std::size_t pos = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz");

  if (pos != std::string::npos)
  {
    std::cout << "The first not in abcdefghijklmnopqrstuvwxyz :" << str[pos] << std::endl;
    std::cout << " position is:" << pos << std::endl;
  }

  return 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、付费专栏及课程。

余额充值