【C】——压缩字符串
编一个函数,输入一个字符串,要求做一个新字符串,把其中所有的一个或多个连续的空白字符都压缩为一个空格。这里所说的空白包括空格、'\t'、'\n'、'\r'。例如原来的字符串是:
This Content hoho is ok ok? file system uttered words ok ok ? end.
压缩了空白之后就是:
This Content hoho is ok ok? file system uttered words ok ok ? end.
1 #include <stdio.h> 2 int judge_char(char ch) 3 { 4 int result; 5 switch(ch) 6 { 7 case '\t':result = 0;break; 8 case '\r':result = 0;break; 9 case '\n':result = 0;break; 10 case ' ':result = 0;break; 11 default:result = 1; 12 } 13 return result; 14 } 15 16 char *shrink_space(char *dest, const char *src, int n) 17 { 18 int i = 0; 19 char *tmp = dest; 20 while(i < n && *src != '\0') 21 { 22 if(judge_char(*src)) 23 *tmp++ = *src++; 24 else 25 { 26 if(!judge_char(*(src - 1))) 27 src++; 28 else 29 { 30 *tmp++ = ' '; 31 src++; 32 } 33 } 34 i++; 35 } 36 *tmp = '\0'; 37 return dest; 38 } 39 40 int main(void) 41 { 42 char a[100]; 43 char b[50] = "This \ 44 Content hoho is ok"; 45 printf("%s\n",shrink_space(a,b,50)); 46 }