This short article presents trivial but fast and memory efficient function to compare two strings. Function returns “0” (zero) on success (strings are the same), otherwise function returns the position where different characters occurred.
Example code
#include <stdint.h> #include <assert.h> static int8_t xstrcmp(const char *s1, const char *s2) { while(*s1 != '\0' && *s1 == *s2) {s1++; s2++;} return (*s1 - *s2); } int main(void) { assert(xstrcmp("test", "test") == 0); // the same assert(xstrcmp("test", "123") != 0); // different return (0); }
This assumes s1 string to be longer than s2. Otherwise you would have to test for string terminator even for s2.
No, it does not assume it. If *s2 is a string terminator and *s1 not, *s1 differs from *s2 and the result is that they differ