Search code examples
cstringcomparisonstring-comparisonstrcmp

strncmp don't work as it should


I'm having problems using strncmp. As I read, theorically strncmp should return 0 if the characters compared of two strings are equal; however, when I do the comparation, the code misbehaves and makes a false positive (Not being equal the characters, still makes the if clause). Here the code:

#include <stdio.h>
#include <string.h>

int main(){
    char *frase1="some string";
    char *frase2="another string";
    char *frase3="some other string";

//Comparar frases desde inicio
    if(strncmp(frase1, frase2, 200))printf("1<->2, 200 characters\n");
    if(strncmp(frase1, frase3, 20))printf("1<->3, 20 characters\n");
    if(strncmp(frase1, frase3, 4))printf("1<->3, 4 characteres\n");

    return 0;
}

If the strings are equal (At least the compared characters), they should print the message; if not, do nothing; so I still don't understand why the first Condition becomes true.

Any ideas?


Solution

  • strcmp & strncmp functions return 0 if strings are equal. You should do:

    if (strncmp(frase1, frase3, 4) == 0) ...
    

    i.e.:

    char *str1 = "Example 1";
    char *str2 = "Example 2";
    char *str3 = "Some string";
    char *str4 = "Example 1";
    
    if (strncmp(str1, str2, 7) == 0) printf("YES\n");  // "Example" <-> "Example"
    else printf("NO\n");
    
    if (strncmp(str1, str3, 2) == 0) printf("YES\n");  // "Ex" <-> "So"
    else printf("NO\n");
    
    if (strcmp(str1, str4) == 0) printf("YES\n");      // "Example 1" <-> "Example 2"
    else printf("NO\n");
    

    yields YES, NO, YES.