C语言实现字符串查找 - strrindex 函数

问题描述:

编写一个函数 strrindex(s,t),用于返回字符串 t 在字符串 s 中最右边出现的位置。该位置从 0 开始计数,如果 s 中不含有 t,那么返回 -1。在你编写的程序中,使用 strrindex(s,t) 函数,输入 ts,输出 ts 中最右边的位置。

输入形式:

控制台分行输入字符串 st

输出形式:

控制台输出一个整数,是 ts 最右边出现的位置。

样例输入:

The strdup() function new returns a pointer to a new string
new

样例输出:

49

样例说明:

输入的第一行为字符串 s,第二行为字符串 t='new'。ts 中出现过两次,其中在最右边出现的位置中'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;
}
C语言实现字符串查找 - strrindex 函数

原文地址: https://www.cveoy.top/t/topic/o0ef 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录