Create a function for comparing character strings
I want to create a function equivalent to the function strcmp available with # include <string.h>.
Code:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
char comparison (ch, cha);
int main (int argc, char * argv [])
(
char string1 [10], string2 [10];
printf ( "Enter two words in validating one after the other, below: \ n");
scanf ( "% 10s% 10s", string1, string2);
printf ( "You took the words% s and% s \ n", string1, string2);
compare (string1, string2);
/ / Function comparison
char comparison (ch, cha)
(
if (ch == CHAINED)
(
printf ( "comparing:% s and% s are identical \ n", ch, cha);
)
else
(
printf ( "comparing:% s and% s are different \ n", ch, cha);
)
)
Outside, if I compare two strings of similar nature, the program reports me as different. Can you tell me where is the mistake?
Re: Create a function for comparing character strings
You can not compare 2 strings like that! If you want to reproduce strcmp you have compare it, Suppose we have 2 character that have value as 'hello' and 'hello', In your comparison function you'll compare : s and b > Not equal you can say that the strings are different, no need to test other characters.
If it was: 'hi' and salt 'comparison:
- s and s -> Equal to continue
- a and a -> Equal to continue
- l and l -> Equal to continue
- u and t -> Not equal it stops there
Re: Create a function for comparing character strings
To Create a function for comparing character strings follow the example given below:
Code:
char *s1, *s2;
char* s = "Hello";
s[1] = 'a';
s = new char[strlen("Hello") + 1];
strcpy(s, "Hello");
if(!strcmp(s1, s2))
Re: Create a function for comparing character strings
You have misunderstood the use of the loop. Here is another function based on function to returns 0 if identical, another value if different:
Code:
SCMP int (char * ch1, char * ch2)
(
while ((* ch1 - ch2 *) & & (* ch1! = '\ 0'))
(Ch1 + +; ch2 + +;)
return (* ch1 - ch2 *);
)