Hi! I've been working through the C Programming Language Second Edition, and I'm stumped on one of the exercises. Exercise 3-3 has me baffled. The task is as follows:
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.
So far I've written the expand function as:
However, for some reason if I pass it a string like a-z0-9, it is adding on -9 at the end of it. My output would be: abcdefghijklmnopqrstuvwxyz0123456789-9Code:void Expand(char s1[], char s2[]) { int i = 0; int y = 0; while((s2[i++] = 0) != '\0') /* clear s2 */ ; for(i = 0; s1[i] != '\0'; ) { int start = s1[i++]; /* advance i until a new type is found to handle cases like a-b-c-d */ if(isdigit(start)) { for( ; isdigit(s1[i]) || s1[i] == '-'; i++) ; } else if(islower(start)) { for( ; islower(s1[i]) || s1[i] == '-'; i++) ; } else if(isupper(start)) { for( ; isupper(s1[i]) || s1[i] == '-'; i++) ; } else { /* if they are not the same type, exit the function */ printf("Invalid character\n"); return; } int end = s1[i-1]; /* check if start and end are the same type, and don't go over bounds */ if(isdigit(start) && isdigit(end)) { while(start <= end) s2[y++] = start++; } else if(islower(start) && islower(end)) { while(start <= end) s2[y++] = start++; } else if(isupper(start) && isupper(end)) { while(start <= end) s2[y++] = start++; } else { printf("Invalid character"); return; } } return; }
Can someone please help me diagnose the problem, I'm completely baffled.



LinkBack URL
About LinkBacks




