21xrx.com
2024-09-20 00:55:22 Friday
登录
文章检索 我的文章 写文章
C++中的字符串查找函数
2023-07-05 09:37:59 深夜i     --     --
C++ 字符串 查找函数

在C++中,字符串是常见的数据类型之一,我们经常需要查找字符串中特定字符或子串的位置。C++提供了许多用于字符串查找的函数,这些函数是标准库的一部分,可以大大简化我们的开发工作。

1. find函数

find函数是C++中最基础的字符串查找函数,它可以用于查找一个字符或一个字符串在目标字符串中第一次出现的位置。该函数的语法如下:


string::size_type find(const string& str, string::size_type pos = 0) const;

该函数的第一个参数是要查找的字符串,第二个参数是查找的起始位置,默认为0。该函数返回查找到的位置,如果没有找到则返回string::npos。

示例代码:


string str = "Hello, World!";

string search = "World";

string::size_type found = str.find(search);

if (found != string::npos)

  cout << "Found at position: " << found << endl;

else

  cout << "Not found." << endl;

2. rfind函数

rfind函数与find函数类似,不同之处在于它从目标字符串的末尾开始查找,找到第一个匹配的子串后立即停止。该函数的用法与find函数相同。

3. find_first_of函数

find_first_of函数用于查找字符串中第一次出现目标字符集中任意一个字符的位置。该函数的语法如下:


string::size_type find_first_of(const char* str, string::size_type pos = 0) const;

string::size_type find_first_of(const string& str, string::size_type pos = 0) const;

第一个参数可以是一个null-terminated C字符串,也可以是一个标准字符串。该函数返回第一次找到的位置,如果没有找到则返回string::npos。

示例代码:


string str = "Hello, World!";

string search = "aeiou";

string::size_type found = str.find_first_of(search);

if (found != string::npos)

  cout << "Found at position: " << found << endl;

else

  cout << "Not found." << endl;

4. find_last_of函数

find_last_of函数与find_first_of函数类似,不同之处在于它从目标字符串的末尾开始查找。该函数的用法与find_first_of函数相同。

5. find_first_not_of函数

find_first_not_of函数用于查找目标字符串中第一个不在指定字符集中的字符的位置。该函数的语法如下:


string::size_type find_first_not_of(const char* str, string::size_type pos = 0) const;

string::size_type find_first_not_of(const string& str, string::size_type pos = 0) const;

第一个参数可以是一个null-terminated C字符串,也可以是一个标准字符串。该函数返回第一个不匹配的字符的位置,如果没有找到则返回string::npos。

示例代码:


string str = "Hello, World!";

string search = "HeloWrd";

string::size_type found = str.find_first_not_of(search);

if (found != string::npos)

  cout << "Found at position: " << found << endl;

else

  cout << "Not found." << endl;

6. find_last_not_of函数

find_last_not_of函数与find_first_not_of函数类似,不同之处在于它从目标字符串的末尾开始查找。该函数的用法与find_first_not_of函数相同。

总结:

C++中提供了多种字符串查找函数,可以根据实际需要选择合适的函数。这些函数不仅能够快速地查找目标字符或子串的位置,还可以处理各种边缘情况,避免出现错误。使用这些函数可以使代码更加简洁、易于维护。

  
  

评论区

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