Hi, I'm following the K&R book and I'm on excersise 3-3 creating an expand function.
Here's what I have so far:
Code:
// my_expand.c
/* program to take a given expression and parse it
* into the entire range. e.g. a-z = abcdef...xyz.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int check_validation(char *pointer); // validate the input
char *expand(char *s1, char *s2); // prototype of function (expand())
int main(int argc, char **argv)
{
if ((argc < 2) || (argc > 2))
{
fprintf(stderr, "Usage: %s <expression> e.g. a-z, 1-9 or A-Z0-9\n", argv[0]);
return -1; // check that the right num of args are there
}
char result[40];
if (check_validation(argv[1]) != 1)
{
fprintf(stderr, "Usage: %s <expression> e.g. a-z, 1-9 or A-Z0-9\n", argv[0]);
return -1;
} else
{
printf("The expression used: %s\n", argv[1]);
printf("And the result: %s\n", expand(argv[1], result));
return 0;
}
}
int check_validation(char *pointer) // function to validate input
{
if (((strlen(pointer)) != 3) || (strlen(pointer) != 6))
return -1;
int i, j;
for (i = 0; i < strlen(pointer); i++)
{
if ((i == 0 || i == 2) || (i == 3 || i == 5))
{
if ((i > 0) && (i != 3))
{
if ((pointer[i] - pointer[i-2]) > (('z' - 'a') || ('9' - '0')))
return -1;
else if ((pointer[i] - pointer[i-2] <= 0))
return -1;
}
else if ((pointer[i] >= 'a') && (pointer[i] <= 'z'))
break;
else if ((pointer[i] >= 'A') && (pointer[i] <= 'Z'))
break;
else if ((pointer[i] >= '0') && (pointer[i] <= '9'))
break;
else
return -1;
} else if (i == 1 || i == 4)
{
switch(pointer[i])
{
case '-':
break;
default:
return -1;
break;
}
}
}
return 1;
}
char *expand(char *s1, char *s2) // write the expand function to return result
{
int i = 0;
while (s1[i] != s1[i+2])
s2[i] = *s1[i++];
i = s1[i+2] - s1[i];
if (strlen(s1) == 6)
{
int j = 3;
while (s1[j] != s1[j+2])
s2[i] = *s1[i++];
}
return s2;
}
And in the expand() function:
Code:
char *expand(char *s1, char *s2) // write the expand function to return result
{
int i = 0;
while (s1[i] != s1[i+2])
s2[i] = *s1[i++];
i = s1[i+2] - s1[i];
if (strlen(s1) == 6)
{
int j = 3;
while (s1[j] != s1[j+2])
s2[i] = *s1[i++];
}
return s2;
}
say the user types "my_expand a-z" in CMD, then s1[i] should be 'a'.
Is it possible to increment the constant 'a' without incrementing the string s1 so
the next value would be 'b' instead of '-' in the string a-z??
Thanks.