21xrx.com
2025-07-04 02:07:06 Friday
登录
文章检索 我的文章 写文章
C++中的字符串查找函数
2023-07-08 21:38:50 深夜i     17     0
C++ 字符串 查找函数

在C++中,字符串查找是一项重要的功能,很多程序都需要用到该功能来实现各种操作。C++中内置了多种字符串查找函数,其中包括以下几种:

1. find函数:

在string类中,find函数可以用来查找一个字符串在另一个字符串中的位置,其语法如下:

size_t find (const string& str, size_t pos = 0) const noexcept;

其中,str是要查找的字符串,pos是查找的起始位置。如果找到了,则返回该字符串在目标字符串中的位置;如果没找到,则返回string::npos。

举个例子:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1 = "Hello World!";
  string str2 = "World";
  int pos = str1.find(str2);
  if (pos != string::npos)
  
    cout << "Found at position " << pos << endl;
  
  else
  
    cout << "Not found" << endl;
  
  return 0;
}

输出结果为:

Found at position 6

2. strstr函数:

在C++标准库中,strstr函数可以用来查找一个字符串在另一个字符串中的位置,其语法如下:

char* strstr (char* str1, const char* str2);

其中,str1是要查找的目标字符串,str2是要查找的字符串。如果找到了,则返回该字符串在目标字符串中的位置;如果没找到,则返回空指针。

举个例子:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  char str1[] = "Hello World!";
  char str2[] = "World";
  char* pos = strstr(str1, str2);
  if (pos != nullptr)
  
    cout << "Found at position " << pos - str1 << endl;
  
  else
  
    cout << "Not found" << endl;
  
  return 0;
}

输出结果为:

Found at position 6

3. find_first_of函数:

在C++的string类中,find_first_of函数可以用来查找目标字符串中第一个出现在指定字符串中的字符的位置,其语法如下:

size_t find_first_of (const string& str, size_t pos = 0) const noexcept;

其中,str是要查找的目标字符串,pos是查找的起始位置。如果找到了,则返回该字符在目标字符串中的位置;如果没找到,则返回string::npos。

举个例子:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1 = "Hello World!";
  string str2 = "abcde";
  int pos = str1.find_first_of(str2);
  if (pos != string::npos)
  
    cout << "Found at position " << pos << endl;
  
  else
  
    cout << "Not found" << endl;
  
  return 0;
}

输出结果为:

Not found

总的来说,在C++中,有很多种字符串查找函数,开发者可以根据自己的需求选择合适的查找函数来实现自己的程序。

  
  

评论区