《C程序设计语言》 练习3-3

问题描述

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

  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.

  

解题思路

  题目中,速写的形式也就是数组s1中的字符串给出了四种:

   a-z(短横线在两字母中间)

    -a-z(最前方有短横线)

    a-b-c(各个字母中间有短横线)

    a-z0-9(有两个字母中间没有横线)

    我们还可以加一种  a-z-(最后面有短横线)

  其实我们把横线换为横线两端字母省略的字母并放在s2中就ok了,比如a-e,我们让a和e正常复制到s2中,把 - 换为bcd,

但是如果  -  在最前面或最后面就不能替换成别的字符了,需要直接把  -  本身复制到s2中。

  还有一个要注意的地方,char类型,‘a’+1=‘b’

  但是我们不能对数组加一来获取其他字母,比如s1[3]='a',如果我们想获得'b',需要

  state=s1[3];

  state+1='b';

  

代码如下

#include<stdio.h>
#define MAXLEN 100

void getlines(char array[],int maxlen)
{
    int c,i;
    for ( i = 0; i < maxlen-1 && (c=getchar())!=EOF && c!='\n'; i++)
    {
        array[i]=c;
    }
    if (c=='\n')
    {
        array[i++]=c;
    }
    array[i]='\0';
}
void expand(char s1[],char s2[])
{
    int i,j;
    char state;
    char c1_first,c1_last;//短横线左端字母,短横线右端字母
    i=j=0;
    while (s1[i])//s1[i]='\0'时跳出循环
    {
        switch (s1[i])
        {
        case '-':
            if (i==0 || s1[i+1]=='\0')
            {
                s2[j++] = '-';;
            }else
            {
                c1_first=s1[i-1];
                c1_last=s1[i+1];

                for ( state=c1_first; state<c1_last-1; j++)//把‘-’替换为省略的字母
                {
                    state++;
                    s2[j]=state;
                }
            }
            break;
        default:
            s2[j++] = s1[i];
            break;
        }
        i++;
    }
    s2[j]='\0';
}

int main()
{
    int i;
    char s1[100];
    char s2[100];
    printf("请输入速写字符:");
    getlines(s1,MAXLEN);
    expand(s1,s2);
    printf("展开为:");
    for ( i = 0; s2[i]!='\0'; i++)
    {
        printf("%c",s2[i]);
    }
    return 0;
}

  

  

运行结果

  

 

 

猜你喜欢

转载自www.cnblogs.com/jerryleesir/p/12907198.html