Re: String Comparision
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: Sun, 29 Apr 2007 19:23:22 +0100
osmium wrote, On 29/04/07 19:03:
"user34" writes:
Hi all. I am trying to learn C.As a simple exercise i tried to write a code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get modified somehow in the comp function and as a result i am getting incorrect results.
Can anyone please point out the error?
#include<stdio.h>
int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);
}
int main(void)
{
char str[]="Hello";
char str2[]="Hello";
if(comp(str,str2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}
The first problem I note is that the terminating condition on the for loop should be an '\0', signifying end of string. This suggests the middle expression should be something like
*s!='\0' && *t'='\0'
But this doesn't work because we don't know if both strings are the same length. So now we precede your code with something to find the length of the strings.
Actually, you don't have to worry about whether the strings are the same length, of even check for the end of both strings. After all, is the strings are of different lengths then when you get to the end of the shorter string you will find that '\0'!=character.
> But that uses stuff in <string.h>, the very thing you are
trying to avoid! But then note that you are barely using a for loop, it is a force fit. I suggest you rewrite using a while loop. I don't like suggesting new and different ways to attack a problem, but even more, I don't like the code I foresee if the for loop approach is continued.
I consider the primary good attribute of a for loop the index variable. But you don't *use* an index variable.
The approach used by the OP is not bad, it just has an error in it. Using an index variable is also perfectly acceptable IMHO since a decent optimising compiler will happily convert from one to the other depending on what is more efficient for the processor.
--
Flash Gordon
.
- References:
- String Comparision
- From: user34
- String Comparision
- Prev by Date: Re: gets() is dead
- Next by Date: Re: String Comparision
- Previous by thread: Re: String Comparision
- Next by thread: Re: String Comparision
- Index(es):
Relevant Pages
|