编写一个函数strrindex(s,t),用于返回字符串t在字符串s中最右边出现的位置.该位置从0开始计数,如果s中不含有t,那么返回-1;在你编写的程序中,使用strrindex(s,t)函数,输入t,s,输出t在s最右边的位置.c 语言
时间: 2024-06-14 14:05:26 浏览: 21
以下是一个使用C语言编写的函数strrindex(s,t),用于返回字符串t在字符串s中最右边出现的位置:
```c
#include <stdio.h>
#include <string.h>
int strrindex(char s[], char t[]) {
int i, j, k;
int len_s = strlen(s);
int len_t = strlen(t);
for (i = len_s - len_t; i >= 0; i--) {
for (j = i, k = 0; k < len_t && s[j] == t[k]; j++, k++);
if (k == len_t) {
return i;
}
}
return -1;
}
int main() {
char t[] = "rld";
char s[] = "Hello,world!Do you love the world.YES,I love!";
int pos;
pos = strrindex(s, t);
printf("%d", pos);
return 0;
}
```
该程序中,我们首先定义了一个函数strrindex,它接受两个参数s和t,分别表示要搜索的字符串和目标字符串。函数中使用两个循环来进行搜索,外层循环从s的末尾开始,内层循环用于比较s和t中的字符是否相等。如果找到了匹配的位置,就返回该位置的索引值;如果没有找到匹配的位置,就返回-1。
在主函数中,我们定义了两个字符串s和t,并调用strrindex函数来查找t在s中最右边出现的位置。最后,我们使用printf函数将结果打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)