设计并测试一个函数,搜索第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;
}
本文展示了一个C语言程序,该程序定义了一个名为`my_strrchr`的函数,功能类似于标准库中的`strchr`。函数接受两个参数,一个字符串和一个字符,返回字符串中首次出现指定字符的指针。在主函数`main`中,程序会循环接收用户输入的字符,并调用`my_strrchr`在预定义的字符串数组中查找,将找到的字符位置输出。若未找到则提示字符不在数组中。程序会在遇到文件结束符时停止运行。
1327

被折叠的 条评论
为什么被折叠?



