本题要求定义一个函数,在字符串中查找字符,并定位在最后一次找到的位置。
函数接口定义:
char * match(char *s, char ch);
其中s是字符串首地址,ch是要查找的字符。要求函数在字符串s中查找字符ch,如果找到,返回最后一次找到的该字符在字符串中的位置(地址);否则,返回空指针NULL。
裁判测试程序样例:
#include <stdio.h>
char *match(char *s, char ch);
int main(void )
{
char ch, str[80], *p = NULL;
scanf("%s", str);
getchar(); /* 跳过输入字符串和输入字符之间的分隔符 */
ch = getchar(); /* 输入一个字符 */
p = match(str, ch); /* 调用函数match() */
if( p != NULL ){ /* 找到字符ch */
printf("%s\n", p);
}else{
printf("Not Found.\n");
}
return 0;
}
/* 请在这里填写答案 */
输入样例1:
program
r
输出样例1:
ram
输入样例2:
program
x
输出样例2:
Not Found.
#include<string.h>
char * match(char *s, char ch){
int n=strlen(s);
char *a=NULL;
for(int i=n-1;i>=0;i--){
if(s[i]==ch){
a=&s[i];
break;
}
}
return a;
}