strstr函数怎么用
时间: 2023-11-24 21:47:56 浏览: 41
strstr函数是C++中的一个字符串查找函数,它的作用是在一个字符串中查找另一个字符串的第一次出现。使用该函数需要包含头文件string.h。该函数的原型为:char *strstr(char *str1, const char *str2)。其中,str1是被查找的目标字符串,str2是要查找的字符串。如果找到了str2,则该函数返回str2在str1中第一次出现的位置的指针;如果未找到,则返回NULL。下面是一个使用strstr函数的例子:
char str1[] = "hello world";
char str2[] = "world";
char *ptr = strstr(str1, str2);
if (ptr != NULL) {
cout << "找到了:" << ptr << endl;
} else {
cout << "未找到" << endl;
}
在上面的例子中,我们定义了两个字符串str1和str2,然后使用strstr函数在str1中查找str2。如果找到了,则输出找到的位置;否则输出未找到。
相关问题
strstr函数使用方法
strstr函数是C语言中的一个字符串处理函数,其作用是在一个字符串中查找另一个字符串第一次出现的位置。其函数原型为:
```
char *strstr(const char *str1, const char *str2);
```
其中,str1表示要被查找的字符串,str2表示要查找的子字符串。函数返回值为一个指向str2在str1中第一次出现位置的指针,如果str2未在str1中出现,则返回NULL。
使用该函数时,需要注意以下几点:
1. 在使用该函数前,需要确保str1和str2指向的字符串以'\0'结尾,否则可能会导致结果不正确。
2. 在使用该函数时,应该判断函数的返回值是否为NULL,以确保查找到了需要的子字符串。
下面是一个使用strstr函数的例子:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "hello world";
char str2[] = "world";
char *p = NULL;
p = strstr(str1, str2);
if (p != NULL)
{
printf("'%s' is found in '%s' at position %ld.\n", str2, str1, p - str1);
}
else
{
printf("'%s' is not found in '%s'.\n", str2, str1);
}
return 0;
}
```
运行结果为:"'world' is found in 'hello world' at position 6."
C语言 strstr函数使用例子
下面是一个使用 C 语言中的 `strstr` 函数的示例:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello, World!";
char str2[] = "World";
char *result;
result = strstr(str1, str2);
if (result == NULL)
{
printf("'%s' is not found in '%s'\n", str2, str1);
}
else
{
printf("'%s' is found in '%s' at position %ld\n", str2, str1, result - str1);
}
return 0;
}
```
在此示例中,我们首先定义了两个字符串 `str1` 和 `str2`,并声明了一个指针变量 `result`。然后,我们使用 `strstr` 函数在 `str1` 中查找 `str2`。如果 `str2` 在 `str1` 中找到了,`strstr` 函数将返回指向 `str2` 在 `str1` 中第一次出现的位置的指针;否则,它将返回 `NULL`。
在这个示例中,我们使用 `if` 语句来检查 `result` 是否为 `NULL`。如果是,我们打印一条消息,指出 `str2` 在 `str1` 中未找到;否则,我们打印一条消息,指出 `str2` 在 `str1` 中的位置。
输出应该如下所示:
```
'World' is found in 'Hello, World!' at position 7
```