#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;
}
字符串中查找一个特定字符最后一次出现的下标位置,并返回该位置
最新推荐文章于 2023-05-26 12:00:54 发布