Search code examples
cstringstrcmp

Will C match two strings if one has a '\n' but the other doesn't?


Say if two strings are exactly identical in C, except that one of them has a '\n' at the end before the null terminator. If we try to use strcmp to see if the two strings are the same, will strcmp match them as being the same or different?

If it doesn't match it, how can we get around this and ignore the '\n' ?


Solution

  • They wont match. There are a lot of cases, one or multiple \n at start of string or at the end. The most flexible aproach is to trim (strip) both string before comparing. See this answer

    For simple cases the following may work. Is based on an strcmp implementation. It allow multiple \n at the end and can easily be modified to trim other chars, like \r or \t although it fail on situations like strcmp_lf("1234\n", "1234\n\n1234")

     static int is_strend(const char a){
         if (a == '\0') return 1;
         if (a == '\n') return 1;
         //if (a == '\t') return 1;
         //if (a == '\r') return 1;
         return 0;
     }
    
     int strcmp_lf(const char *s1, const char *s2)
     {
         for ( ; *s1 == *s2 || (is_strend(*s1) && is_strend(*s2)); s1++, s2++)
         if (*s1 == '\0' || *s2 == '\0')
             return 0;
         return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
     }