C语言程序设计 第二版 第三章
第三章课后实战,完成全部的函数题(70分);自己选择编程题完成40分即可。
剩余时间:15天
6-3 exercise 3-3 (10分)
Write a function expand(s1,s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc…xyz in s2. Allow for letters of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9 and -a-z. Arrange that a leading or trailing - is taken literally.
函数接口定义:
void expand(char [], char []);
裁判测试程序样例:
#include <stdio.h>
#include <assert.h>
const int N = 10001;
void expand(char [], char []);
int main()
{
// freopen(“0.in”, “r”, stdin);
// freopen(“0.out”, “w”, stdout);
char s1[N], s2[N * 30];
while(scanf("%s", s1) != EOF) {
expand(s1, s2);
printf("%s\n", s2);
}
return 0;
}
/* 请在这里填写答案 */
输入样例:
a-z
A-A
0-9
c–z
输出样例:
abcdefghijklmnopqrstuvwxyz
A
0123456789
c–z
int st(char c);
void expand(char s1[], char s2[])
{
int j = 0, k = 0;
int dd = 7;
while (s1[j] != ‘\0’)
{
if ( (s1[j] == ‘-’)&&(j!=0) )//后面是 --aa 这种情况 即第一个字符是 - 它前面没有字符了
{
if ( (st(s1[j - 1]) == st(s1[j + 1]))&& (st(s1[j - 1]) !=4) )
{
dd = s1[j + 1] - s1[j - 1];
if (dd < 0) {
s2[k] = s1[j];
k++; j++;
}
else
{
for (; s2[k - 1] < (s1[j + 1] - 1); )
{
s2[k] = s2[k - 1] + 1;
k++;
}
if (!dd) j += 2;// 此处是为了 解决 --A 这种情况
else
j++;
}
}
else
{
s2[k] = s1[j];
j++; k++;
}
}
else
{
s2[k] = s1[j];
j++; k++;
}
dd = 7;
}
s2[k] = '\0';
}
int st(char c)
{
if (c >= ‘0’ && c <= ‘9’)
return 1;
else if (c >= ‘a’ && c <= ‘z’)
return 2;
else if (c >= ‘A’ && c <= ‘Z’)
return 3;
else
return 4;状态已经指明了
}