c++中strstr函数用法

c++ 中的 strstr() 函数在指定字符串中搜索子字符串,返回子字符串中第一个字符的位置或 null。函数使用 kmp 算法,先对子字符串进行预处理,提高搜索效率。

c++中strstr函数用法-1

C++ 中 strstr() 函数用法

定义和语法

strstr() 函数用于在一个字符串中查找另一个子字符串的首次出现位置。其语法如下:

char *strstr(const char *str, const char *substr);

其中:

  • str:要搜索的字符串。
  • substr:要查找的子字符串。

返回值

如果找到子字符串,strstr() 函数返回包含子字符串第一个字符的字符串指针,否则返回 NULL。

用法说明

strstr() 函数使用 KMP 算法(Knuth-Morris-Pratt 算法)进行字符串匹配。它先对子字符串进行预处理,然后扫描字符串,从而提高了搜索效率。

示例用法

以下代码示例演示了如何使用 strstr() 函数:

#include 
#include 

using namespace std;

int main() {
  char str[] = "Hello, world!";
  char substr[] = "world";

  char *result = strstr(str, substr);

  if (result) {
    cout 

输出:

Substring 'world' found at position 7

注意事项