11.7 ctype.h字符函数和字符串
ctype.h中有关于处理字符的函数原型。
/* mod_str.c -- modifies a string */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LIMIT 81
void ToUpper(char *);
int PunctCount(const char *);
int main(void)
{
char line[LIMIT];
char * find;
puts("Please enter a line:");
fgets(line, LIMIT, stdin);
find = strchr(line, '\n'); // look for newline
if (find) // if the address is not NULL,
*find = '\0'; // place a null character there
ToUpper(line);
puts(line);
printf("That line has %d punctuation characters.\n",
PunctCount(line));
return 0;
}
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;
}
/* 输出:
*/
根据ANSI C中的定义,toupper()函数只改变小写字符。但是一些很旧的C实现不会自动检查大小写,所以以前的代码通常会这样写:
if( islower( *str ) ) /*ANSI C之前的做法--在转换大小写之前先检查*/
*str = toupper( *str );
顺带一提,ctype.h中的函数通常作为宏(macro)来实现。这些C预处理器宏的作用很像函数,但是两者有一些重要的区别。
该程序使用fgets()和strchr()组合,读取一行输入并把换行符替换成空字符。这种方法与使用s_gets()的区别是:s_gets()会处理输入行剩余字符(如果有的话),为下一次输入做好准备。而本例只有一条输入语句,就没必要进行多余的步骤。