不太懂...
编写函数,实现在字符串str1中寻找字符ch最后出现的位置,如果没有找到ch,则返回-1。在main函数中输入字符串str1和字符ch,然后输出查找到的结果。 谁能帮我解决一下?
程序代码:root@~ #cat 1.c
#include <stdio.h>
#include <string.h>
int main (void) {
char a[]="hello,world!"; //样本字符串
char ch;
int i; //位置
int FindCh (char a[],char ch); //声明函数原型,函数FindCh接受一个字符数组和一个字符,返回一个整数
printf ("Enter a character:"); //输入
ch=getchar();
i=FindCh(a,ch); //函数返回值在i中
if(i==-1) printf ("No Found!\n");//如果返回-1,则显示NoFound,退出
else printf ("Last position is :%i\n",i); //否则, 显示ch所在最后的位置。
return 0;
}
int FindCh (char a[],char ch) {
int i;
i=strlen(a);
while(i>=0) {
if(a[i]==ch) return i;
i--;
}
return -1;
}
root@~ #./1
Enter a character:a
No Found!
root@~ #./1
Enter a character:l
Last position is :9
root@~ #./1
Enter a character:o
Last position is :7
root@~ #./1
Enter a character:2
No Found!
root@~ #