Simple String Compare

Status
Not open for further replies.

AtomSoft

Well-Known Member
Would it be wise to create my own string compare function?

For instance:
Code:
char strCompare(char *str1,char *str2, unsigned char len)
{
	unsigned char x = 0;

	for(x=0;x<len;x++)
	{
		if(*str1++ != *str2++)
			return -1;
	}

	return 0;
}

You think this would give me any problems? It seems to work nice and fast. sometimes i just dont like including files or just dont understand why some things are overcomplicated.
 
That will work fine unless one of the strings is longer than len.

You could do something like,
Code:
char strCompare(char *str1,char *str2){
    unsigned char x = 0;
    do{
        if(*str1 != *str2)
            return -1;
    }while(*str1++ && *str2++)
    return 0;
}
As this ensures the zero terminators are compared as well.

Mike.
 
It would make more sense to return 0 for a mismatch. I just copied Jason's example without really thinking about it.

Mike.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…