问题描述
编写函数expand(s1, s2),将字符串s1中类似于a-z一类的速记符号在字符串s2中扩展为等价的完整列表abc...xyz。该函数可以处理大小写字母和数字,并可以处理a-b-c、a-z0-9与-a-z等类似的情况。作为前导和尾随的-字符原样打印。
问题分解
- 主函数main
- 核心函数 expand(s1, s2)。根据题意,假设s1="-a-z0-9A-D--",那么期望得到的值s2="-abcdefghijklmnopqrstuvwxyz01123456789ABCD--"。观察发现,头尾的-以及各位置上的字母或数字也不变,要做的就是把a-z、0-9、A-D之间的横杆去掉,然后填充横杆两端数字或字母之间的数据。因此,我们的算法描述可以有:
for(i = 0, j= 0; s1[i] != '\0'; i++)
if s1[i] == '-'
if i > 0
if s1[i+1]和s1[i-1] 都在 0-9、a-z、A-Z 区间内
执行 s2[j] = s[j-1] + 1, j++ 直到s2[j] = s1[i + 1]
else
s2[j++] = s1[i]
else
s2[j++] = s1[i]
else
s2[j++] = s1[i]
# 代码实现
#include<stdio.h>
#define LEN 500
void expand(char s1[], char s2[]);
int main()
{
char s1[LEN] = "-a-z0-9B-Y--", s2[LEN];
printf("The input string is: %s \n", s1);
expand(s1, s2);
printf("The output string is: %s \n", s2);
return 0;
}
void expand(char s1[], char s2[])
{
int i,j;
for(i = 0, j = 0; s1[i] != '\0'; i++){
if(s1[i] == '-'){
if(i > 0){
if((s1[i - 1] >= 'a' && s1[i - 1] < 'z' || s1[i - 1] >= 'A' && s1[i - 1] < 'Z' || s1[i - 1] >= '0' && s1[i - 1] < '9' )
&& (s1[i + 1] >= 'a' && s1[i + 1] <= 'z' || s1[i + 1] >= 'A' && s1[i + 1] <= 'Z' || s1[i + 1] >= '0' && s1[i + 1] <= '9' )){
while(s2[j - 1] < s1[i + 1] - 1){
s2[j] = s2[j - 1] + 1;
j++;
}
continue;
}
}
}
s2[j++] = s1[i];
}
s2[j] = '\0';
}