|
发表于 2023-10-10 23:28:24
|
显示全部楼层
strstr 是一个在 C 语言中常用的函数,用于在一个字符串中查找另一个字符串的首次出现。如果找到,它会返回一个指向该出现位置的指针。如果没有找到,它会返回 NULL。
函数原型如下:
- char *strstr(const char *haystack, const char *needle);
复制代码
在这个函数中,haystack 是我们要在其中查找的字符串,而 needle 是我们要查找的字符串。
以下是一个使用 strstr 的例子:
- #include <stdio.h>
- #include <string.h>
- int main() {
- char haystack[40] = "Hello, World! Nice to meet you.";
- char needle[10] = "World";
- char *result;
- result = strstr(haystack, needle);
- if(result) {
- printf("'%s' found at position: %ld\
- ", needle, result - haystack);
- } else {
- printf("'%s' not found.\
- ", needle);
- }
- return 0;
- }
复制代码
在这个例子中,我们在字符串 \"Hello, World! Nice to meet you.\" 中查找 \"World\"。如果找到,我们打印出 \"World\" 的位置;如果没有找到,我们打印出 \"'World' not found.\"。
注意,strstr 返回的是一个指针,所以我们可以通过减去 haystack 的地址来得到 \"World\" 在 haystack 中的位置。
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案 |
|