Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

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.

Latest threads

New Articles From Microcontroller Tips

Back
Top