题目:编写一个接受一个指向字符串的指针作为参数,并返回该字符串的长度的函数。
#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;
}