火星的叛徒百度云盘:C语言问题---扩展字符

来源:百度文库 编辑:高考问答 时间:2024/04/29 21:26:45
【问题描述】
编写一函数expand(s1,s2),用以将字符串s1中的缩记符号在字符串s2中扩展为等价的完整字符,例如将a-d扩展为abcd。该函数可以处理大小写字母和数字,并可以处理a-b-c、a-z0-9与-a-z等类似的情况。在main函数中测试该函数:从键盘输入包含缩记符号的字符串,然后调用该函数进行扩展,输出扩展结果。
(教材 P63:Exercise 3-3)
【输入形式】
从键盘输入包含扩展符的字符串
【输出形式】
输出扩展后的字符串
【输入样例】
a-c-u-B
【输出样例】
abcdefghijklmnopqrstu-B
【样例说明】
扩展输入a-c-u为:abcdefghijklmnopqrstu,而B比u值小,所以无法扩展,直接输出。

#include<stdio.h>

void expand( char *s1, char *s2 ) {
    while( *s2 = *s1 ) {
        char prev = *( s1 - 1 ),
             curr = *s1,
             next = *( s1 + 1 );

        if( curr == '-' && prev < next ) {
            char c = prev + 1;
        
            while( c < next )
                *s2++ = c++;
            --s2;
        }
        ++s1;
        ++s2;
    }
}

int main( ) {
    char in[99],
         out[99];

    gets( in );
    expand( in, out );
    printf( "%s\n", out );
}

简单得很哦