C PRIMER PLUS第十一章第5题自定义strrchr

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计并测试一个函数,搜索第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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值