holyya.com
2025-09-04 10:19:34 Thursday
登录
文章检索 我的文章 写文章
C++标准库中的字符串查找操作
2023-07-05 09:14:29 深夜i     --     --
C++ 标准库 字符串 查找 操作

C++标准库提供了丰富的字符串查找操作,使得字符串处理变得简单高效。下面介绍几个常用的字符串查找函数。

1. find函数

find函数可以在一个字符串中查找另一个字符串,并返回第一个匹配的位置。它有多个重载形式,可以指定搜索的起始位置和搜索的字符数。用法如下:


string str = "Hello, world! This is C++.";

string substr = "world";

size_t pos = str.find(substr);

if (pos != string::npos)

  // found

else

  // not found

2. rfind函数

rfind函数与find函数类似,但是从末尾开始搜索,并返回最后一个匹配的位置。用法与find函数类似。

3. find_first_of函数

find_first_of函数可以在一个字符串中查找另一个字符串中任意一个字符,并返回第一个匹配的位置。用法如下:


string str = "Hello, world! This is C++.";

string chars = "abc";

size_t pos = str.find_first_of(chars);

if (pos != string::npos)

  // found

else

  // not found

4. find_last_of函数

find_last_of函数与find_first_of函数类似,但是从末尾开始搜索,并返回最后一个匹配的位置。用法与find_first_of函数类似。

5. find_first_not_of函数

find_first_not_of函数可以在一个字符串中查找第一个不在另一个字符串中的字符,并返回其位置。用法如下:


string str = "Hello, world! This is C++.";

string chars = "Helo, !";

size_t pos = str.find_first_not_of(chars);

if (pos != string::npos)

  // found

else

  // not found

6. find_last_not_of函数

find_last_not_of函数与find_first_not_of函数类似,但是从末尾开始搜索,并返回最后一个匹配的位置。用法与find_first_not_of函数类似。

总之,C++标准库中的字符串查找操作可以方便地实现字符串处理。需要注意的是,一些函数的返回值可能为string::npos,表示没有找到匹配的位置。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复