C程序设计语言(第二版)3-3

3-3 编写函数expand(s1,s2),将字符串s1中类似与a-z一类的速记符号在字符串s2中扩展成等价的完整列表abc...xyz。该函数可以处理大小写字母和数字,并可以处理a-b-c、a-z0-9与-a-z等类似的情况

 

#include<stdio.h>
#include<string.h>

void expand(char* result,char* s2);

int main()
{
    char *s[] = { "a-d-", "a-b-c","z-a-", "-1-6-", 
                  "a-ee-a", "a-R-L", "1-9-1", 
                  "5-5", NULL }; 
    char result[100]=""; 
    int i = 0; 
     
    while ( s[i] ) { 
        expand(result, s[i]); 
      printf("Unexpanded: %s\n", s[i]); 
      printf("Expanded  : %s\n", result); 
		 printf("helloworld\n");
        ++i; 
    }
	return 0;
}

void expand(char * s1, char* s2)
{
	static char upper[27]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	static char lower[27]="abcdefghigklmnopqrstuvwxyz";
	static char digits[11] = "0123456789"; 

	int i=0;
	int j=0;
	char *start;
	char *end;
	char *p;
	while(s2[i]){
		switch(s2[i]){
		case '-':
			if(i==0 || s2[i+1]=='\0')
			{
				s1[j]='-';
				j++;
				i++;
				break;
			}
			else
			{
				if( (start = strchr(upper,s2[i-1])) && (end = strchr(upper,s2[i+1])))//如果不存在strchr()返回null
					;
				else if( (start = strchr(lower,s2[i-1])) && (end = strchr(lower,s2[i+1])))
					;
				else if( (start = strchr(digits,s2[i-1])) && (end = strchr(digits,s2[i+1])))
					;
				else{
					fprintf(stderr, "EX3_3: Mismatched operands '%c-%c'\n", s2[i-1], s2[i+1]); 
                    s1[j++] = s2[i-1]; 
                    s1[j++] = s2[i++]; 
                    break; 
				}

				p=start;
				while(p!=end){
					s1[j]=*p;
					if(start<end)
						p++;
					else
						p--;
					j++;
				}
				s1[j]=*end;
				j++;
				s1[j]='-';
				i=i+2;
			}
			break;
		default:
			if ( s2[i+1] == '-' && s2[i+2] != '\0' ) { 
                ++i; 
            } 
            else {      
                s1[j++] = s2[i++]; 
            } 
            break; 
		}
	}
	s1[j] = s2[i];
	i++;

}

 PS 本例中用到了string.h 中的strchr(str,c)函数,用于查找字符c在字符串str中首次出现的位置的指针,如果找不到,则返回null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值