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

练习 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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值