DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

String Equality Tester

  • submit to reddit
        If you want to test the equality of two strings and don't want the overhead of strcmp(), then this is the function for you.
_Bool strequals(char* a, char* b) {
 if (!a || !b) return 0;
 do {if (*a != *b) return 0; } while (*a++ && *b++);
 return 1;


Snippets Manager replied on Sat, 2009/05/02 - 1:40am

Quickly wrote two methods: bool strequals(const char* a, const char* b) { if (!a || !b) return 0; do {if (*a != *b) return 0; } while (*a++ && *b++); return 1; } bool string_comp(const string &a, const string &b) { return a == b; } Compared a couple of strings in a loop a million times with each method above and the result is: Time spent strequals: 0.007564 Time spent string_comp: 0.000434

Snippets Manager replied on Mon, 2007/08/06 - 4:57am

No.. it will work fine. However, "the overhead of strcmp" is dubious, I'd take a punt that this would be slower than the one provided by the library.

Snippets Manager replied on Fri, 2007/08/03 - 6:57am

What will happen in case of two different lenght strings like: "mystring" and "mystring2"? I thing it will return also true even the strings are not