题目来源:http://acm.hdu.edu.cn/diy/contest_showproblem.php?cid=31654&pid=1002&hide=1&problem=Problem%20B
解法或类型:
Description
在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
1. 把每个单词的首字母变为大写。
2. 把数字与字母之间用下划线字符(_)分开,使得更清晰
3. 把单词中间有多个空格的调整为1个空格。
Input
我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。每个单词间由1个或多个空格分隔。假设用户输入的串长度不超过200个字符。
Output
请按照题意进行输出。
Sample Input
you and me what cpp2005program
this is a 99cat
Sample Output
You And Me What Cpp_2005_program
This Is A 99_cat
题意描述
给一段英文,把每个单词的首字母变成大写,数字与字母之间用 _ 隔开,如果有连续的空格把它删除的剩一个。
解题思路
先判断第一个字符是数字还是空格,字母让给做出相应的变化,然后用一个循环从第二个字符开始判断第一个字符是数字还是空格,如果是首字母变大写,是连续空格把除最后一个空格除外的其他空格变成*,然后输出*不输出,字母和数字之间加_.
时空分析:
程序代码:
#include<stdio.h>
#include<string.h>
int main()
{
charstr1[1000],str2[1000];
int i,l,t;
while(gets(str1)!=NULL)
{
t=0;
l=0;
memset(str2,0,sizeof(str2));
if(str1[0]>='a'&&str1[0]<='z'&&str1[1]>='0'&&str1[1]<='9')
{
l=1;
printf("%c_",str1[0]-32);
}
if(str1[0]>='a'&&str1[0]<='z'&&l!=1)
{
printf("%c",str1[0]-32);
}
if(str1[0]>='0'&&str1[0]<='9'&&str1[1]>='a'&&str1[1]<='z')
{
t=1;
printf("%d_",str1[0]-'0');
}
if(str1[0]>='0'&&str1[0]<='9'&&t!=1)
printf("%d",str1[0]-'0');
if(str1[0]==' '&&str1[1]!=' ')
{
printf(" ");
}
for(i=1;str1[i]!='\0';i++)
{
str2[i]=str1[i];
if(str1[i-1]==' '&&str1[i]>='a'&&str1[i]<='z')
str2[i]=str1[i]-32;
if(str1[i]==' '&&str1[i+1]==' ')
{
str2[i]='*';
}
if(str1[i]>='0'&&str1[i]<='9')
{
//str2[i+1]='_';
str2[i]=str1[i];
}
}
for(i=1;str2[i]!='\0';i++)
{
if(str2[i]!='*')
printf("%c",str2[i]);
if(str2[i]>='0'&&str2[i]<='9'&&str2[i+1]>='a'&&str2[i+1]<'z')
{
printf("_");
}
if(str2[i]>='A'&&str2[i]<='z'&&str2[i+1]>='0'&&str2[i+1]<'9')
{
printf("_");
}
}
printf("\n");
}
return 0;
}错误分析:
1、开始第一个字符忽略了空格,数字的情况。
2、没看清题以为只有数字在前字母在后才加_.