蓝桥杯 -- 串的处理

串的处理
 

在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
1. 把每个单词的首字母变为大写。
2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
3. 把单词中间有多个空格的调整为1个空格。


例如:
用户输入:
you and     me what  cpp2005program
则程序输出:
You And Me What Cpp_2005_program


用户输入:
this is     a      99cat
则程序输出:
This Is A 99_cat


我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。每个单词间由1个或多个空格分隔。
假设用户输入的串长度不超过200个字符。

 

解题思路:在原串上处理,先将首字母改成大写。然后输出的时候完成后两个条件。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <ctype.h>
 4 int main()
 5 {
 6     char str[210];
 7     int i;
 8     while (gets(str)!=NULL)  // 读入一个串 
 9     {
10         if (isalpha(str[0]))      // 判断第一个单词的首字母是否在下标0处 
11             str[0] = str[0]-'a'+'A';
12         int len = strlen(str);
13         for (i = 1; i < len; i ++)
14             if (isalpha(str[i]) && str[i-1] == ' ')   // 在原串中完成第一个条件 
15                 str[i] = str[i]-'a'+'A';    
16         for (i = 0; i < len; i ++)
17         {
18             if (str[i] != ' ' && str[i+1] == ' ')  // 如果出现空格,只输出一个 
19                 printf("%c ",str[i]);
20             else if ((isalpha(str[i])&&isdigit(str[i+1])) || (isalpha(str[i+1])&&isdigit(str[i])))
21                 printf("%c_",str[i]);               // 在数字和字母之间加上‘—’ 
22             else
23             {
24                 if (str[i] != ' ')        
25                     printf("%c",str[i]);
26             }
27         }
28         printf("\n");
29     }
30     return 0;
31 }

 

posted @ 2017-04-08 17:34  gaoyanliang  阅读(420)  评论(0编辑  收藏  举报