Why does my string comparison fail?

后端 未结 4 681
予麋鹿
予麋鹿 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:17

    You can use strncmp:

    if (!strncmp(sub_str[j], "max_n=20", 9)) {
    

    Note the 9 is the length of the comparison string plus the final '\0'. strncmp is a little bit safer than strcmp because you specify how many comparisons will be made at most.

    0 讨论(0)
  • 2020-12-21 11:27

    You can't use == to compare strings in C. You must use strcmp.

    for (j=0; j<=i; j++) { 
       if (strcmp(sub_str[j], "max_n=20") == 0) { 
          printf("substring %d is %s\n", j, sub_str[j]); 
       } 
    } 
    
    0 讨论(0)
  • 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 <stdio.h>
    #include <string.h>
    
    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;
    }
    
    0 讨论(0)
  • 2020-12-21 11:31

    You can't compare strings in C with == operator. You need to use strcmp function or strncmp.

    0 讨论(0)
提交回复
热议问题