《C primer plus》的字符串习题

题目:编写一个接受一个指向字符串的指针作为参数,并返回该字符串的长度的函数。

#include <stdio.h>
int strlen(char * str);
int main(void)
{
	int i;
	char *str = "I love you";
	i = strlen(str);
	printf("%d", i);

	return 0;
}
int strlen(char * str)
{
	int i = 0;
	while (*str != '\0')
	{
		i++;
		str++;
	}
	
	return i;	
}

运行无误

设计一个函数,接受一个指向字符串的指针,返回指向该字符串第1个空格字符的指针,或如果未找到空格字符,则返回空指针

char * kong(char * str)
{
	char * find;
	find = strchr(str, ' ');

	return find;
}

好像有点问题,strchr函数不确定是否只返回第一个空格字符的指针

对照参考解答

char * strblk(char * string)
{
	while (*string != ' ' && *string != '\0')
		string++;
	if (*string == '\0')
		return NULL;
	else
		return string;
}

用了while循环准确的判断出第一个空格字符

题目13:重写程序清单11.21,使用ctype.h头文件中的函数,以便无论用户选择大写还是小写,该程序都能正确识别答案

11.21程序
#include <stdio.h>
#include <string.h>

#define ANSWER "Grant"
#define SIZE 40
char * s_gets(char * st, int n);

int main(void)
{
	char try[SIZE];

	puts("Who is buried in Grant's tomb?");
	s_gets(try, SIZE);
	while (strcmp(try, ANSWER) != 0)//strcmp比较两个字符串,相同返回0
	{
		puts("No, that's wrong. Try again.");
			s_gets(try, SIZE);

	}
	puts("That's right!");

		return 0;
}

char * s_gets(char * st, int n)
{
	char * ret_val;
	int i = 0;

	ret_val = fgets(st, n, stdin);
	if (ret_val)
	{
		while (st[i] != '\n' && st[i] != '\0')
			i++;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

先来看看ctype.h头文件中的函数

tolower()toupper()
如果参数是大写字符,该函数返回小写字符;否则返回原始参数如果参数是小写字符,该函数返回大写字符;否则,返回原始参数

改写如下:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define LIMIT 81

#define ANSWER "Grant"
#define SIZE 40
char * s_gets(char * st, int n);
void ToUpper(char * str);
int PunctCount(const char * str);

int main(void)
{
	char trey[SIZE];
	char instead[SIZE] = ANSWER;
	puts("Who is buried in Grant's tomb?");
	s_gets(trey, SIZE);
	ToUpper(trey);
	ToUpper(instead);

	while (strcmp(trey, instead) != 0)
	{
		puts("No, that's wrong. Try again.");
		s_gets(trey, SIZE);
	}
	puts("That's right!");


	return 0;
}
char * s_gets(char * st, int n)
{
	char * ret_val;
	int i = 0;

	ret_val = fgets(st, n, stdin);
	if (ret_val)
	{
		while (st[i] != '\n' && st[i] != '\0')
			i++;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}
void ToUpper(char * str)
{
	while (*str)
	{
		*str = toupper(*str);
		str++;
	}
}
int PunctCount(const char * str)
{
	int ct = 0;
	while (*str)
	{
		if (ispunct(*str))
			ct++;
		str++;
	}
	return ct;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值