Determining when string equality comparison fails
Given these lines
char * foo = "The Name of the Game";
char * boo = "The Name of the Rose"
I want to determine the address of the first non-matching character in order to extract the common header ("Name").
I know that a hand-coded loop is trivial, but I'm curious if there is any option strcmp()
or other library function that will do this automatically for me? And the answer to any question in C ++?
+3
source to share
3 answers
I believe this simple function will do what you want using strncmp
.
(slightly tested ...)
int find_mismatch(const char* foo, const char* boo)
{
int n = 0;
while (!strncmp(foo,boo,n)) { ++n; }
return n-1;
}
int main(void)
{
char * foo = "The Name of the Game";
char * boo = "The Name of the Rose";
int n = find_mismatch(foo,bar);
printf("The strings differ at position %d (%c vs. %c)\n", n, foo[n], boo[n]);
}
Output The string differ at position 16 (G vs. R)
0
source to share
I believe you can use strspn (str1, str2), which returns the length of the initial part of str1, which consists of only parts of str2.
char *foo = "The Name of the Game";
char *boo = "The Name of the Rose";
size_t len = strspn(foo, boo);
printf("The strings differ after %u characters", (unsigned int)len);
-2
source to share