字符串中查找一个特定字符最后一次出现的下标位置,并返回该位置

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

/*****************************************************************************
函数功能:字符串中查找一个特定字符最后一次出现的下标位置,并返回该位置;
函数参数:srcStr原字符串;ch要查找的字符;
函数返回值:成功:返回该字符在字符串中的下标;失败:返回unsigned int的最大值
*****************************************************************************/
unsigned int lastLocationOfChar(char srcStr[], char ch);

int main()
{
    char srcArray[100] = {0};
    printf("Please input a string:\n");
    scanf("%s", srcArray);

    char ch = '\0';
    printf("Please input a char in here:\n");
    getchar();
    scanf("%c", &ch);

    unsigned int location = lastLocationOfChar(srcArray, ch);
    printf("srcstr:%s\t------char:%c\t------location:%u\n", srcArray, ch, location);

    return 0;
}

unsigned int lastLocationOfChar(char srcStr[], char ch)
{
    size_t strLenth = strlen(srcStr);
    if(strLenth == 0 || ch == '\0') {
        printf("Please check the parameter.\n");
        return UINT_MAX;    // 返回unsigned int的最大极值
    }

    int retIndex = 0;
    for (int i = strLenth - 1; i >= 0; i--) {
        if(srcStr[i] == ch) {
            retIndex = i;
            break;
        } else {
            retIndex = UINT_MAX;
        }
    }
    return retIndex;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值