-
Copy to Buffers
I am writng a fucntion that Compares two strings alphabetically, case-INsensitive.
The instructions are :
* Copy the two strings to local buffers (arrays), change both string *COPIES to upper case; Compare the two strings using myStrCmp().
Code:
int myStrBlindCmp(unsigned char change_one[], unsigned char change_two[])
{
}
is what i have :p
i know that to change to uppercase would look like this:
Code:
// To Uppercase
for ( x=0; string[x] != '\0'; ++x)
if ( string[x] >= 'a' && string[x] <= 'z')
string[x] = string[x] - (32);
and myStrCmp looks like this:
Code:
int myStrCmp (unsigned char one[],unsigned char two[])
{
int i=0,x=0;
while (one[i]==two[i] && one[i] != '\0' && two[i] != '\0')
++i;
if (one[i] == '\0' && two[i] =='\0')
x=0;
else
if (one[i] > two[i] )
x=1;
else
x= -1;
return (x);
}
but how do you copy to local buffers and put this all together???
-
>i know that to change to uppercase would look like this
Maybe 20 years ago. These days we do this:
Code:
for (x = 0; string[x] != '\0'; ++x)
string[x] = toupper((unsigned char)string[x]);
>but how do you copy to local buffers and put this all together???
You have to bring out the big guns:
Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int my_stricmp(const char *a, const char *b)
{
int la = strlen(a) + 1;
int lb = strlen(b) + 1;
char *ca = malloc(la);
char *cb = malloc(lb);
int i;
for (i = 0; i < la; i++)
ca[i] = (char)toupper((unsigned char)a[i]);
for (i = 0; i < lb; i++)
cb[i] = (char)toupper((unsigned char)b[i]);
i = strcmp(ca, cb);
free(ca);
free(cb);
return i;
}
int main(void)
{
char *a = "test";
char *b = "TeSt";
printf("%d\n", my_stricmp(a, b));
return 0;
}
-
The olny reason i actually wrote it out was because i had to. I am not allowed to use ToUpper or ToLower... also i am not allowed to use pointers which makes it more difficult
-
>I am not allowed to use ToUpper or ToLower...
I don't know why teachers still assign this exercise. ASCII isn't a ubiquitous standard, so it would be better to just explain how such a conversion would be made in ASCII and then allow the students to use portable functions as they would in the real world.
>also i am not allowed to use pointers which makes it more difficult
No, it makes it impossible if you still want to copy the strings. Have you considered not making a copy in favor of handling each character in order?
Code:
while (toupper(a[i]) == toupper(b[i])) {
if (a[i++] == '\0')
return 0;
}
if (a[i] < b[i])
return -1;
else
return +1;
Since you already know how to perform the conversion, writing your own toupper for convenience is trivial.