【问题描述】
从键盘输入包含扩展符'-'的字符串,将其扩展为等价的完整字符,例如将a-d扩展为abcd,并输出扩展后的字符串。
要求:只处理[a-z]、[A-Z]、[0-9]范围内的字符扩展,即只有当扩展符前后的字符同时是小写字母、大写字母或数字,并且扩展符后的字符大于扩展符前的字符时才进行扩展,其它情况不进行扩展,原样输出。例如:a-R、D-e、0-b、4-B等字符串都不进行扩展。
【输入形式】
从键盘输入包含扩展符的字符串
【输出形式】
输出扩展后的字符串
【输入样例1】
ADEa-g-m02
【输出样例1】
ADEabcdefghijklm02
【输入样例2】
cdeT-bcd
【输出样例2】
cdeT-bcd
【样例说明】
将样例1的输入ADEa-g-m02扩展为:ADEabcdefghijklm02;样例2的输入cdeT-bcd中,扩展符前的字符为大写字母,扩展符后的字符为小写字母,不在同一范围内,所以不进行扩展。
【评分标准】
该题要求扩展字符,提交程序文件expand.c
【思路】
1.使用gets()函数读取后遍历判断。
2.根据题目描述注意“-”符号前后为同一类型才扩展,判断清楚此点即可。
3.注意遍历时的策略,检查少输出或者重复输出。
【运行代码】
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1024
char str[MAX];//读入存储
char ans[MAX];//答案
int cnt=0;
int main()
{
gets(str);
int len=strlen(str);
for(int i=0;i<len;i++)
{
if(str[i+1]=='-')//遍历到的下一位是'-'时
{
if(str[i]>='a'&&str[i]<='z')//小写字符判断
{
if(str[i+2]>=str[i]&&str[i+2]<='z')//是同一类型判断
{
for(int p=0;p<(int)str[i+2]-(int)str[i];p++)
{
ans[cnt++]=str[i]+p;
}
i++;
}
else{//不是同一类型时,将str[i]与str[i+1]读入ans中,遍历到'-'后一位的字符
ans[cnt++]=str[i];
ans[cnt++]=str[i+1];
i++;
}
}
/*后续两种判断与第一种类似*/
/*大写字符判断*/
else if(str[i]>='A'&&str[i]<='Z')
{
if(str[i+2]>=str[i]&&str[i+2]<='Z')
{
for(int p=0;p<(int)str[i+2]-(int)str[i];p++)
{
ans[cnt++]=str[i]+p;
}
i++;
}
else{
ans[cnt++]=str[i];
ans[cnt++]=str[i+1];
i++;
}
}
/*数字判断*/
else if(isdigit(str[i]))
{
if(str[i+2]>=str[i]&&str[i+2]<='9')
{
for(int p=0;p<(int)str[i+2]-(int)str[i];p++)
{
ans[cnt++]=str[i]+p;
}
i++;
}
else{
ans[cnt++]=str[i];
ans[cnt++]=str[i+1];
i++;
}
}
}
else{
ans[cnt++]=str[i];
}
}
puts(ans);/*输出ans*/
return 0;
}