练习 3-3
编写函数 expand(s1, s2),将字符串 s1 中类似于 a-z 一类的速记符号
在字符串 s2 中扩展为等价的完整列表 abc…xyz。该函数可以处理大小写字母和数字,并可
以处理 a-b-c、a-z0-9 与-a-z 等类似的情况。作为前导和尾随的-字符原样排印。
那个if有点长,我叠了三层,主要是判断“-”前后的字符是否匹配
那三个判断函数逻辑很简单,后面会贴上来
isDigital:判断是不是数字
isLowwer:判断是不是小写字母
isUpper:判断是不是大写字母
void expand(char s1[], char s2[])
{
int i, j, c;
i = j = 0;
while (s1[i] != '\0')
{
if (s1[i] == '-')
{
if (isDigital(s1[i - 1]) && isDigital(s1[i + 1])
|| isLowwer(s1[i - 1]) && isLowwer(s1[i + 1])
|| isUpper(s1[i - 1]) && isUpper(s1[i + 1]))
{
for (c = s1[i - 1] + 1; c <= s1[i + 1]; c++)//扩展速记符号
{
s2[j++] = c;
}
i += 2; //扩展完成,跳过已扩展的速记符号
}
else // "-" 前后不匹配,原样记录
{
s2[j++] = s1[i++];
s2[j++] = s1[i++];
}
}
else
{
s2[j++] = s1[i++];
}
}
s2[j] = '\0';
}
完整代码 :
/*练习 3-3 编写函数 expand(s1, s2),将字符串 s1 中类似于 a-z 一类的速记符号
在字符串 s2 中扩展为等价的完整列表 abc…xyz。该函数可以处理大小写字母和数字,并可
以处理 a-b-c、a-z0-9 与-a-z 等类似的情况。作为前导和尾随的-字符原样排印。
*/
#include <stdio.h>
void expand(char s1[], char s2[]);
int isDigital(int c);
int isLowwer(int c);
int isUpper(int c);
main()
{
char s1[] = "-a-b-c-a-z \n 0-9 \n A-Z- \n a-5 \n h-k";
char s2[500];
expand(s1, s2);
printf("%s\n", s2);
}
void expand(char s1[], char s2[])
{
int i, j, c;
i = j = 0;
while (s1[i] != '\0')
{
if (s1[i] == '-')
{
if (isDigital(s1[i - 1]) && isDigital(s1[i + 1]) || isLowwer(s1[i - 1]) && isLowwer(s1[i + 1]) || isUpper(s1[i - 1]) && isUpper(s1[i + 1]))
{
for (c = s1[i - 1] + 1; c <= s1[i + 1]; c++)//扩展速记符号
{
s2[j++] = c;
}
i += 2; //扩展完成,跳过已扩展的速记符号
}
else // "-" 前后不匹配,原样记录
{
s2[j++] = s1[i++];
s2[j++] = s1[i++];
}
}
else
{
s2[j++] = s1[i++];
}
}
s2[j] = '\0';
}
int isDigital(int c)
{
if (c >= '0' && c <= '9')
return 1;
else
return 0;
}
int isLowwer(int c)
{
if (c >= 'a' && c <= 'z')
return 1;
else
return 0;
}
int isUpper(int c)
{
if (c >= 'A' && c <= 'Z')
return 1;
else
return 0;
}