为什么我的字符串比较失败?

时间:2010-11-01 14:47:18

标签: c

假设我有以下代码和输出:

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

输出

substring 0 is max_n=20
substring 1 is max_m=20

现在我只想打印一些子串。但是,如果我尝试有条件地这样做:

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

我根本没有输出。我的代码出了什么问题?

4 个答案:

答案 0 :(得分:6)

您无法使用==来比较C中的字符串。您必须使用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]); 
   } 
} 

答案 1 :(得分:5)

您无法将C中的字符串与==运算符进行比较。您需要使用strcmp函数或strncmp

答案 2 :(得分:3)

确保使用strncmp而不是strcmp。 strcmp非常不安全

BSD联机帮助页(任何nix都会给你这个信息):

man strncmp

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

strcmp()和strncmp()函数按字典顺序比较以null结尾的字符串s1和s2。

strncmp()函数比较不超过n个字符。因为strncmp()用于比较字符串而不是二进制数据,所以不会比较出现在'\ 0'字符后面的字符。

strcmp()和strncmp()返回一个大于,等于或小于0的整数,因为字符串s1大于,等于或小于字符串s2。使用无符号字符进行比较,以便\200' is greater than \ 0'。

来自: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;
}

答案 3 :(得分:2)

您可以使用strncmp

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

注意9是比较字符串的长度加上最终的'\0'strncmpstrcmp更安全一点,因为您指定最多会进行多少次比较。

相关问题