c语言

c语言locate函数的用法是什么

小亿
110
2023-10-25 09:35:54
栏目: 编程语言

C语言中的`locate`函数并不存在。也许你指的是`strstr`函数,它用于在一个字符串中查找另一个字符串的位置。

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

```c

#include

char *strstr(const char *haystack, const char *needle);

```

该函数接受两个参数:`haystack`和`needle`。`haystack`是要搜索的字符串,`needle`是要查找的子字符串。

函数返回一个指向第一次出现`needle`子字符串的位置的指针。如果未找到匹配,则返回`NULL`。

以下是一个示例:

```c

#include

#include

int main() {

    const char *haystack = "This is a sample string";

    const char *needle = "sample";

    char *result = strstr(haystack, needle);

    if (result != NULL) {

        printf("'%s' found at index %ld\n", needle, result - haystack);

    } else {

        printf("'%s' not found\n", needle);

    }

    return 0;

}

```

输出将是:

```

'sample' found at index 10

```

请注意,在使用 `strstr` 函数之前,确保目标字符串以及要查找的子字符串都已经以 null 终止。

0
看了该问题的人还看了