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

C++ 中 strstr() 函数用法
定义和语法
strstr() 函数用于在一个字符串中查找另一个子字符串的首次出现位置。其语法如下:
<code class="cpp">char *strstr(const char *str, const char *substr);</code>
其中:
立即学习“C++免费学习笔记(深入)”;
-
str:要搜索的字符串。 -
substr:要查找的子字符串。
返回值
如果找到子字符串,strstr() 函数返回包含子字符串第一个字符的字符串指针,否则返回 NULL。
用法说明
strstr() 函数使用 KMP 算法(Knuth-Morris-Pratt 算法)进行字符串匹配。它先对子字符串进行预处理,然后扫描字符串,从而提高了搜索效率。
示例用法
以下代码示例演示了如何使用 strstr() 函数:
<code class="cpp">#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "Hello, world!";
char substr[] = "world";
char *result = strstr(str, substr);
if (result) {
cout << "Substring '" << substr << "' found at position " << (result - str) << endl;
} else {
cout << "Substring not found" << endl;
}
return 0;
}</code>输出:
<code>Substring 'world' found at position 7</code>
注意事项
- strstr() 函数区分大小写。
- 如果子字符串为空,strstr() 函数将返回原始字符串的指针。
- 如果子字符串比字符串长,strstr() 函数将返回
NULL。











