strstr函数的用法例子

admin 31 0

`strstr` 是一个常用的字符串函数,用于在字符串中查找子串,如果找到子串,则返回子串的指针;否则返回 `NULL`。

以下是 `strstr` 函数的用法示例:

```c

#include

#include

int main() {

char str[] = "Hello, world!";

char sub[] = "world";

char *result = strstr(str, sub);

if (result != NULL) {

printf("Substring found at position: %ld\n", result - str + 1);

} else {

printf("Substring not found.\n");

}

return 0;

}

```

在上面的示例中,我们定义了一个字符串 `str` 和一个子串 `sub`,我们使用 `strstr` 函数在 `str` 中查找 `sub`,如果找到子串,则返回子串的指针;否则返回 `NULL`,在示例中,我们检查返回的指针是否为 `NULL`,如果不是,则打印子串在原字符串中的位置。