strstr函数的用法c++
时间: 2025-03-26 16:28:17 浏览: 33
### C++ 中 `strstr` 函数的使用方法
在C++标准库中,`strstr` 是用于在一个字符串中查找另一个字符串首次出现的位置。此函数返回指向第一次匹配子串的第一个字符的指针;如果未找到,则返回空指针。
下面是一个简单的例子来展示如何使用 `strstr` 函数:
```cpp
#include <iostream>
#include <cstring> // 包含了C风格字符串处理功能
int main() {
const char* source = "This is a simple example.";
const char* target = "simple";
const char* result = strstr(source, target);
if(result != nullptr){
std::cout << "Found substring at position: "
<< result - source << '\n';
} else {
std::cout << "Substring not found.\n";
}
}
```
上述程序会输出 `"Found substring at position: 10"` 表明目标字符串 `"simple"` 开始于源字符串中的第11个位置(索引从零开始计数)。当找不到指定模式时则输出 `"Substring not found."`[^1]。
对于更复杂的场景,比如实现自己的 `strStr()` 方法而不是调用内置的 `strstr` 函数,可以参照给定的例子进行理解并编写相应的逻辑。
阅读全文
相关推荐


















