C语言实现字符串查找 - strrindex 函数
C语言实现字符串查找 - strrindex 函数
问题描述:
编写一个函数 strrindex(s,t),用于返回字符串 t 在字符串 s 中最右边出现的位置。该位置从 0 开始计数,如果 s 中不含有 t,那么返回 -1。在你编写的程序中,使用 strrindex(s,t) 函数,输入 t 和 s,输出 t 在 s 中最右边的位置。
输入形式:
控制台分行输入字符串 s 和 t。
输出形式:
控制台输出一个整数,是 t 在 s 最右边出现的位置。
样例输入:
The strdup() function new returns a pointer to a new string
new
样例输出:
49
样例说明:
输入的第一行为字符串 s,第二行为字符串 t='new'。t 在 s 中出现过两次,其中在最右边出现的位置中'new'的第一个字符'n'在 s 中所在的位置为 49。
代码:
#include <stdio.h>
#include <string.h>
int strrindex(char s[], char t[]) {
int i, j, k, pos = -1;
for (i = 0; s[i] != '\0'; i++) { // 遍历s字符串
for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++) { // 匹配t字符串
// 如果匹配成功且已经匹配到t的最后一个字符,记录当前位置
if (t[k+1] == '\0') {
pos = i;
}
}
}
return pos;
}
int main() {
char s[100], t[100];
scanf('%[^
]%*c', s); // 读入字符串s
scanf('%[^
]%*c', t); // 读入字符串t
int pos = strrindex(s, t);
printf('%d\n', pos);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/o0ef 著作权归作者所有。请勿转载和采集!