- 论坛徽章:
- 0
|
本帖最后由 xiaowh00 于 2012-06-20 11:26 编辑
Exercise 3-3. 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.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
/* author: xiaowh0 */
/* date: 2012-6-20 */
/* 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 */
void expand(char[],char[]);
main()
{
int i,c;
char s1[MAX],s2[MAX];
i=0;
while((c=getchar())!=EOF)
{
if(c!='\n')
s1[i++]=c;
}
s1='\0';
expand(s1,s2);
printf("%s\n",s2);
}
void expand(char s1[],char s2[])
{
int i,j;
i=j=0;
while(s1!='\0')
{
if(s1>='a' && s1<='z')
{
s2[j]=s1;
if(s1[i+1]=='-' && s1[i+2]!='\0')
{
i=i+2;
if(s2[j]>s1 || (s1<'a' || s1 > 'z'))
{
printf("You use range %c must large than %c\n",s1,s2[j]);
exit(1);
}
while(s2[j]<s1)
{
s2[j+1]=s2[j]+1;
j++;
}
}
else
{
i++;
j++;
}
}
else if(s1>='A' && s1<='Z')
{
s2[j]=s1;
if(s1[i+1]=='-' && s1[i+2]!='\0')
{
i=i+2;
if(s2[j]>s1 || (s1<'A' || s1>'Z'))
{
printf("You use range %c must large than %c\n",s1,s2[j]);
exit(1);
}
while(s2[j]<s1)
{
s2[j+1]=s2[j]+1;
j++;
}
}
else
{
i++;
j++;
}
}
else if(s1>='0' && s1<='9')
{
s2[j]=s1;
if(s1[i+1]=='-' && s1[i+2]!='\0')
{
i=i+2;
if(s2[j]>s1 || (s1<'0' || s1>'9'))
{
printf("You use range %c must large than %c\n",s1,s2[j]);
exit(1);
}
while(s2[j]<s1)
{
s2[j+1]=s2[j]+1;
j++;
}
}
else
{
i++;
j++;
}
}
else
{
s2[j]=s1;
i++;
j++;
}
}
} |
|