Get a pointer to the first char, which is different from the two C lines

Is there a stardard C function that compares two strings of C and returns a pointer to the first character that is different, and NULL if the strings are equal?

#include <stdio.h>
int main()
{
    const char *p, *s1 = "foobar", *s2 = "foobaz";

    p = strdiffchr(s1, s2);
    if (!p)
        puts("the strings are equal");
    else
        printf("s1 has %c, where s2 has %c\n", *p, s2[p - s1]);

    return 0;
}

EDIT: I chose the following solution:

char *strdiffchr(const char *s1, const char *s2)
{
    while (*s1 && *s1 == *s2) {
        s1++;
        s2++;
    }
    return (*s1 == *s2) ? NULL : (char *)s1;
}
+3
source share
2 answers

I do not think there is such a function. Encoding can be performed in one cycle for, but:

const char *p1, *p2, *s1 = "foobar", *s2 = "foobaz";
for (p1 = s1, p2 = s2 ; *p1 && *p1 == *p2 ; p1++, p2++)
    ; // Loop body is empty, because everything is done in the header.
const char *p = *p1 || *p2 ? p1 : NULL;

Demo on ideon.

+6
source

May be:

int findIndexOfMismatch(const char *a, const char *b) {
    int i = 0;
    while (a[i] == b[i] && a[i])
       i++;
    return a[i] || b[i] ? i : -1;
}

This returns -1if two rows match. This returns an index, not a pointer; you can instead return a pointer: for example:

    return a[i] || b[i] ? a + i : 0; // NB: pointer to a, not b, or null if equal
+2
source

All Articles