C程序设计语言(第二版)3-3
时间:2010-07-16 来源:carolaif
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
相关阅读 更多 +










