strstr_tail
时间: 2024-02-25 18:50:38 浏览: 21
strstr_tail是一个C语言函数,用于在字符串中查找指定子字符串的最后一次出现位置。它的函数原型如下:
```c
char *strstr_tail(const char *haystack, const char *needle);
```
该函数接受两个参数,分别是待搜索的字符串haystack和要查找的子字符串needle。函数会在haystack中从后往前查找needle,并返回最后一次出现的位置的指针。如果找不到needle,则返回NULL。
下面是一个使用strstr_tail函数的示例:
```c
#include <stdio.h>
#include <string.h>
char *strstr_tail(const char *haystack, const char *needle) {
int haystack_len = strlen(haystack);
int needle_len = strlen(needle);
if (needle_len > haystack_len) {
return NULL;
}
for (int i = haystack_len - needle_len; i >= 0; i--) {
if (strncmp(haystack + i, needle, needle_len) == 0) {
return (char *)(haystack + i);
}
}
return NULL;
}
int main() {
const char *haystack = "Hello, world!";
const char *needle = "world";
char *result = strstr_tail(haystack, needle);
if (result != NULL) {
printf("Found at position: %ld\n", result - haystack);
} else {
printf("Not found\n");
}
return 0;
}
```
上述示例中,我们在字符串"Hello, world!"中查找子字符串"world"的最后一次出现位置,并打印出结果。输出结果为"Found at position: 7",表示"world"最后一次出现在位置7。