The C Programming Language 练习题3-3

时间:2021-08-10 00:09:44

题目
编写函数 expand(s1, s2),将字符串s1 中类似于a-z 一类的速记符号在字符串s2中扩展为等价的完整列表abc…xyz。该函数可以处理大小写字母和数字,并可以处理a-b-c、a-z0-9与-a-z等类似的情况。作为前导和尾随的-字符原样排印。

题目分析
逐个读取字符串1中的字符,如果初现‘-’则判断下位是什么。a-c-e我理解为要输出abcde这样的序列。

代码实现

#include <stdio.h>
#define MAXLINE 1000

void expandtest(char s1[], char s2[]);

int main()
{
    int i;
    char c, s1[MAXLINE], s2[MAXLINE];

    i = 0;
    while ((c = getchar()) != EOF && i < MAXLINE)
        s1[i++] = c;
    s1[i] = '\0';
    for (i = 0; s1[i] != '\0'; i++)
        printf("%c", s1[i]);
    expandtest(s1, s2);
    for (i = 0; s2[i] != '\0'; i++)
        printf("%c", s2[i]);
}

void expandtest(char s1[], char s2[])
{
    char c, d;
    int i, j, m, n, num;

    i = j = 0;
    while(s1[i] != '\0' && i < MAXLINE)
    {
        if (s1[i] != '-')
            s2[j] = s1[i], j++;
        else if ((s1[i] == '-') && (i == 0))
            s2[j] = '-';
        else if ((s1[i] == '-') && (s1[i+1] != '-'))
        {
            c = s1[i-1];
            d = s1[i+1];
            n = d - c -1;
            if ( n < 0)
                s2[j++] = '-';
            while (n > 0)
                {
                    s2[j] = c + 1;
                    c++;
                    j++;
                    n--;
                }

        }
        i++;
    }
    s2[j] = '\0';

}

测试结果

输入:
a-b-cefa-f-lmn-f-a0-9ABC-F
^Z
输出:
a-b-cefa-f-lmn-f-a0-9ABC-F
abcefabcdefghijklmn-f-a0123456789ABCDEF