在c++中string的find怎么用
时间: 2023-03-24 15:00:46 浏览: 62
在 C 语言中,可以使用标准库中的字符串函数来查找一个字符串中是否包含另一个字符串。
其中,`strstr()` 函数可以用来查找一个字符串中是否包含另一个字符串。它的语法如下:
```c
char *strstr(const char *haystack, const char *needle);
```
其中,`haystack` 是要被查找的字符串,`needle` 是要查找的子串。如果 `needle` 存在于 `haystack` 中,则该函数返回 `needle` 在 `haystack` 中第一次出现的地址;否则返回 `NULL`。
例如,下面的代码演示了如何使用 `strstr()` 函数查找一个字符串中是否包含另一个字符串:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "hello world";
char str2[20] = "world";
char *ptr;
ptr = strstr(str1, str2);
if (ptr != NULL) {
printf("'%s' is found in '%s' at position %ld.\n", str2, str1, ptr - str1);
} else {
printf("'%s' is not found in '%s'.\n", str2, str1);
}
return 0;
}
```
输出结果为:
```
'world' is found in 'hello world' at position 6.
```
上面的代码中,`strstr()` 函数返回了 `str2` 在 `str1` 中第一次出现的地址,通过计算该地址与 `str1` 的起始地址之间的偏移量,可以得到 `str2` 在 `str1` 中的位置。