strstr函数
时间: 2023-06-30 18:19:41 浏览: 151
strstr函数是C标准库中的一个函数,用于在一个字符串中查找另一个字符串的第一次出现。该函数的原型为:
```
char *strstr(const char *str1, const char *str2);
```
其中,str1表示要查找的字符串,str2表示要搜索的字符串。该函数返回一个指向第一次出现字符串 str2 的指针,如果未找到,则返回 NULL。
例如,以下代码可以在字符串 str 中查找第一次出现子串 substr 的位置:
```
char str[] = "hello world";
char substr[] = "world";
char *result = strstr(str, substr);
if (result != NULL) {
printf("Found at position %ld\n", result - str);
} else {
printf("Not found\n");
}
```
输出结果为:
```
Found at position 6
```
说明子串 "world" 在字符串 "hello world" 中的位置是从第 6 个字符开始的。
相关问题
C语言函数strstr函数
`strstr`是C语言标准库函数之一,它定义在头文件`string.h`中。这个函数用于在一个字符串(也称为"haystack")中查找另一个字符串("needle")首次出现的位置。如果找到了匹配的子串,它会返回指向该子串首字符的指针;如果没有找到,就返回`NULL`。
函数原型通常像这样:
```c
char *strstr(const char *haystack, const char *needle);
```
这里的`haystack`是要搜索的主字符串,`needle`是需要查找的子字符串。例如:
```c
char str[] = "Hello, world!";
char* found = strstr(str, "world");
if (found) {
printf("Substring found at position %ld\n", (long)(found - str));
} else {
printf("Substring not found.\n");
}
```
这将输出:`Substring found at position 7`,因为"world"是在`str`数组从位置7开始的部分找到的。
strstr函数写法
`strstr()` 函数是 C 标准库中的字符串搜索函数,它在查找第一个子串出现在主串的位置。这个函数原型通常是这样的:
```c
char *strstr(const char *haystack, const char *needle);
```
参数说明:
- `haystack`:要在其中搜索的主串("haystack"),也称为"haystack"。
- `needle`:要查找的目标子串("needle")。
返回值:
- 如果找到目标子串,`strstr()` 返回指向该子串的第一个字符的指针。
- 如果未找到,它会返回 `NULL`。
示例用法:
```c
#include <string.h>
#include <stdio.h>
int main() {
const char *str1 = "Hello, world!";
const char *searchStr = "world";
char *result = strstr(str1, searchStr);
if (result) {
printf("'%s' found at position %ld in '%s'.\n", searchStr, result - str1, str1);
} else {
printf("'%s' not found in '%s'.\n", searchStr, str1);
}
return 0;
}
```
在这个例子中,如果子串 "world" 存在于 `str1` 中,程序会打印出它的位置;如果没有找到,则提示未找到。记得包含 `<string.h>` 来使用 `strstr()`。
阅读全文
相关推荐















