一个字符串中查找另一个字符串的最后一次出现位置的函数
时间: 2024-03-25 11:38:22 浏览: 19
C语言中没有提供直接查找字符串中最后一次出现位置的函数,但可以通过组合使用其他函数来实现该功能。
例如,可以使用strrchr函数查找字符串中最后一个字符的位置,然后再使用strstr函数查找子字符串在该位置之前的最后一次出现位置。示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int find_last_occurrence(const char *str, const char *substr)
{
char *last_char = strrchr(str, substr[strlen(substr)-1]);
if(last_char != NULL)
{
char *ptr = strstr(str, substr);
while(ptr != NULL && ptr <= last_char)
{
last_char = ptr;
ptr = strstr(ptr+1, substr);
}
return last_char - str;
}
else
{
return -1;
}
}
int main()
{
char str[] = "hello world, world is beautiful";
char substr[] = "world";
int pos = find_last_occurrence(str, substr);
if(pos >= 0)
{
printf("最后一次出现位置为:%d\n", pos);
}
else
{
printf("没有找到字符串 %s\n", substr);
}
return 0;
}
```
输出结果为:
```
最后一次出现位置为:19
```
说明在字符串"hello world, world is beautiful"中找到了子字符串"world",并且最后一次出现位置是从索引19开始的。