Why does my string comparison fail?

后端 未结 4 748
予麋鹿
予麋鹿 2020-12-21 10:50

Let\'s say I have the following code and output:

for (j = 0; j <= i; j++) 
    printf(\"substring %d is %s\\n\", j, sub_str[j]);

4条回答
  •  温柔的废话
    2020-12-21 11:30

    Make certain you use strncmp and not strcmp. strcmp is profoundly unsafe.

    BSD manpages (any nix will give you this info though):

    man strncmp
    
    int strncmp(const char *s1, const char *s2, size_t n);
    

    The strcmp() and strncmp() functions lexicographically compare the null-terminated strings s1 and s2.

    The strncmp() function compares not more than n characters. Because strncmp() is designed for comparing strings rather than binary data, characters that appear after a `\0' character are not compared.

    The strcmp() and strncmp() return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters, so that \200' is greater than\0'.

    From: http://www.codecogs.com/reference/c/string.h/strcmp.php?alias=strncmp

    #include 
    #include 
    
    int main()
    {
      // define two strings s, t and initialize s
      char s[10] = "testing", t[10];
    
      // copy s to t
      strcpy(t, s);
    
      // test if s is identical to t
      if (!strcmp(s, t))
        printf("The strings are identical.\n");
      else
        printf("The strings are different.\n");
    
      return 0;
    }
    

提交回复
热议问题