1. 程式人生 > >ctype.h字符函數和字符串

ctype.h字符函數和字符串

line mit str hat void type ring cte character

ctype.h存的是與字符相關的函數;

這些函數雖然不能處理整個字符串,但是可以處理字符串中的字符;

ToUpper()函數,利用toupper()函數處理字符串中的每個字符,轉換成大寫;

PunctCount()函數,利用ispunct()統計字符串中的標點符號個數;

使用strchr()處理fgets()讀入字符串的換行符;這樣處理沒有把緩沖區的剩余字符清空,所以僅適合只有一條輸入語句的情況。s_gets()適合處理多條輸入語句的情況

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <ctype.h>
 4
#define LIMIT 81 5 6 void ToUpper(char *); 7 int PunctCount(const char *); 8 9 int main(void) 10 { 11 char line[LIMIT]; 12 char * find; 13 14 puts("Please enter a line:"); 15 fgets(line,LIMIT,stdin); 16 find = strchr(line, \n); 17 if(find) 18 *find =\0; 19 ToUpper(line);
20 puts(line); 21 printf("That line has %d punctuation characters.\n",PunctCount(line)); 22 23 return 0; 24 } 25 26 void ToUpper(char * str) 27 { 28 while(*str) 29 { 30 *str =toupper(*str); 31 str++; 32 } 33 } 34 35 int PunctCount(const char * str) 36 { 37 int
ct =0; 38 while(*str) 39 { 40 if(ispunct(*str)) 41 ct++; 42 str++; 43 } 44 45 return ct; 46 }

ctype.h字符函數和字符串