设计并测试一个函数,搜索第1个函数形参指定的字符串,在其中查找第2个函数形参指定的字符首次出现的位置。如果成功,该函数返回指向该字符的指针,如果在字符串中未找到指定字符,则返回空指针(该函数的功能与strchr相同)。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。
以下为代码:(control+z退出)
#include <stdio.h>
#define SIZE 81
char * my_strrchr(const char * st, char ch); //一定不会修改字符串用const
int main(void)
{
const char arr[SIZE] = {"uyuyig6sytdyf6tg7z"};
const char * ptr;
char ch;
printf("Enter the character you want to search(end of file to quit): ");
while((ch = getchar()) != EOF)
{
while(getchar() != '\n') //吸收多余输入与换行符
continue;
ptr = my_strrchr(arr, ch);
if(ptr)
printf("the address of first %c in the array is %p.\n", ch, ptr);
else
printf("These is no %c in the array.\n");
printf("Enter the character you want to search(end of file to quit): ");
}
puts("Done");
return 0;
}
char * my_strrchr(const char * st, char ch)
{
const char * ret_val = st;
while(ret_val <= st + SIZE) //包含字符串末尾的'\0',虽然从键盘不能输入这个
{
if(*ret_val == ch)
return ret_val;
ret_val++;
}
return NULL;
}