C语言实现字符串查找:strrindex函数
#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++) {
for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (k > 0 && t[k] == '\0') {
pos = i;
}
}
return pos;
}
int main() {
char s[100], t[100];
printf("请输入字符串s:");
scanf("%s", s);
printf("请输入字符串t:");
scanf("%s", t);
int pos = strrindex(s, t);
if (pos == -1) {
printf("字符串s中不含有字符串t\n");
} else {
printf("字符串t在字符串s中最右边的位置是:%d\n", pos);
}
return 0;
}
本文介绍了用C语言编写的strrindex函数,该函数用于查找字符串t在字符串s中最右边出现的的位置。代码中首先定义了strrindex函数,函数使用两个嵌套循环遍历字符串s,内层循环用于判断字符串t是否为字符串s的子串,并记录子串的起始位置。如果找到子串,则更新pos的值为子串的起始位置。最后返回pos的值,即字符串t在字符串s中最右边出现的的位置。
在main函数中,首先从用户输入两个字符串s和t,然后调用strrindex函数查找字符串t在字符串s中最右边出现的的位置,并将结果输出。
代码示例中使用了一个简单的示例字符串,读者可以尝试使用其他字符串进行测试。
希望本文能够帮助读者理解C语言中字符串查找的基本方法。
原文地址: https://www.cveoy.top/t/topic/o0cU 著作权归作者所有。请勿转载和采集!