C Primer Plus 第六版 第十一章 编程练习

本文提供了16个C语言编程练习,涵盖字符串操作、字符处理、输入输出等方面。练习包括读取字符数组、查找特定字符、字符串包含判断、字符串反序、删除空格、单词计数等任务,旨在提升C语言编程技能。
摘要由CSDN通过智能技术生成

1.设计并测试一个函数,从输入中获取n个字符(包括空白、制表符、换行符),把结果储存在 一个数组里,它的地址被传递作为一个参数。

#include <stdio.h>
void input(char * p, int n)
{
	int i = 0;

	for (i = 0;i < n;i++)
		scanf("%c", &p[i]);
}

//测试函数
#define SIZE 10
int main(void)
{
	char arr[SIZE];
	int i;
	input(arr, SIZE);

	for (i = 0;i < SIZE;i++)
		printf("%c", arr[i]);

	return 0;
}

2.修改并编程练习1的函数,在n个字符后停止,或在读到第1个空白、制表符或换行符时停止, 哪个先遇到哪个停止。不能只使用scanf()。

#include <stdio.h>
void input(char* p, int n)
{
	int i;

	for (i = 0;i < n;i++)
	{
		p[i] = getchar();
		if (p[i] == ' ' || p[i] == '/t' || p[i] == '\n')
			break;
	}
}

//测试函数
#define SIZE 10
int main(void)
{
	char arr[SIZE];
	int i;

	input(arr, SIZE);
	for (i = 0;i < SIZE;i++)
		printf("%c ", arr[i]);

	return 0;
}

3.设计并测试一个函数,从一行输入中把一个单词读入一个数组中,并丢弃输入行中的其余字符。该函数应该跳过第1个非空白字符前面的所有空白。将一个单词定义为没有空白、制表符或换行符的字符序列。

#include <stdio.h>
#define SIZE 20
void input_word(char word[SIZE])
{
	int i = 0;

	while ((word[i] = getchar()) == ' ' || word[i] == '\t' || word[i] == '\n')
		continue;
	while (scanf("%c", &word[i + 1]) == 1 && word[i + 1] != ' ' && word[i + 1] != '\t' && word[i + 1] != '\n'&&i<SIZE-2)
		i++;
	word[i+1]='\0';
	while (getchar() != '\n')
		continue;
}

//测试函数
int main(void)
{
	char word[SIZE];
	input_word(word);
	puts(word);

	return 0;
}

4.设计并测试一个函数,它类似编程练习3的描述,只不过它接受第2个参数指明可读取的最大字符数。

#include <stdio.h>
void input_word(char word[], int n)
{
	int i = 0;

	while ((word[i] = getchar()) == ' ' || word[i] == '\t' || word[i] == '\n')
		continue;
	while (scanf("%c", &word[i + 1]) == 1 && word[i + 1] != ' ' && word[i + 1] != '\t' && word[i + 1] != '\n' && i < n - 1)
		i++;
	word[i + 1] = '\0';
	while (getchar() != '\n')
		break;
}

//测试函数
#define SIZE 20
int main(void)
{
	char word[SIZE];

	input_word(word, 10);
	puts(word);

	return 0;
}

5.设计并测试一个函数,搜索第1个函数形参指定的字符串,在其中查找第2个函数形参指定的字符首次出现的位置。如果成功,该函数返回指向该字符的指针,如果在字符串中未找到指定字符, 则返回空指针(该函数的功能与strchr()函数相同)。在一个完整的程序中测试该函数,使用一个 循环给函数提供输入值。

#include <stdio.h>
char * str_chr(char* str, char c)
{
	while (*str != c && *str != '\0')
		str++;
	if (*str == c)
		return str;
	else
		return NULL;
}
//测试函数
#define SIZE 20
int main(void)
{
	char c;
	char input[SIZE];
	char * find;
	puts("Enter the character:");
	scanf("%c",&c);
	getchar();
	puts("Enter the string(empty line to quit):");
	while (fgets(input,SIZE,stdin) && input[0] != '\0')
	{
		find = str_chr(input, c);
		if (find != NULL)
			printf("Address of %c is %p.\n", c, find);
		else
			printf("NULL po
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值