【问题标题】:Using strcmp on a subset of a string对字符串的子集使用 strcmp
【发布时间】:2015-04-17 03:40:03
【问题描述】:

我想使用strcmp 将一个字符串的子集与另一个字符串进行比较。

说我有:

a[] = {'h','e','l','l','o',' ','w','o','r','l',d'};

和

b[] = {'w','o','r','l','d};

我想将a 的第二个单词与整个字符串b 进行比较。我知道a 中第二个单词的起始索引。有没有办法直接使用strcmp 来做到这一点,或者需要先在a 上做更多的事情?

【问题讨论】:

  • 你应该使用strncmp( a+6, b, 5 )

标签: c arrays string strcmp


【解决方案1】:

a 和 b 是 char 数组,但它们不是字符串,因为它们不是以空值结尾的。

如果它们被修改为像这样以空结尾:

char a[] = {'h','e','l','l','o',' ','w','o','r','l','d', '\0'};

char b[] = {'w','o','r','l','d', '\0'};

而a的第二个词的索引如你所说是已知的,那么是的,你可以用strcmp(a + 6, b)来比较。

【讨论】:

    【解决方案2】:
    if (strcmp((a + index), b) == 0) { ... }
    

    strcmp 需要两个指针,所以你直接添加索引。

    但是,您应该为每个字符串添加一个终止 NULL 字节。

    【讨论】:

      【解决方案3】:

      假设这些是实际上字符串而不是没有字符串终止符的字符数组,这很容易做到。

      你说你没有世界上w的索引,所以这是一个问题:

      strcmp (b, a+index)
      

      或:

      strcmp (b, &(a[index]))
      

      取决于您认为哪个更好读(底层代码应该几乎相同)。

      例如,看看这个程序:

      #include <stdio.h>
      #include <string.h>
      
      int main (void) {
          char *str1 = "world";
          char *str2 = "hello world";
      
          for (size_t i = 0; i < strlen (str2); i++)
              printf ("%s on match '%s' with '%s'\n",
                  strcmp (str1, str2+i) ? "No " : "Yes",
                  str1, str2+i);
      
          return 0;
      }
      

      哪个输出:

      No  on match 'world' with 'hello world'
      No  on match 'world' with 'ello world'
      No  on match 'world' with 'llo world'
      No  on match 'world' with 'lo world'
      No  on match 'world' with 'o world'
      No  on match 'world' with ' world'
      Yes on match 'world' with 'world'
      No  on match 'world' with 'orld'
      No  on match 'world' with 'rld'
      No  on match 'world' with 'ld'
      No  on match 'world' with 'd'
      

      无论它们是字符串文字还是正确终止的字符数组都没有区别。将两个声明行替换为:

      char str1[] = {'w','o','r','l','d','\0'};
      char str2[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
      

      同样有效。

      如果它们没有正确终止,str... 调用就不是真正适合使用的调用。

      【讨论】:

      • 如果这些是以空字符结尾的字符数组,同样的方法是否可行?
      • @PythonNewb,是的,它会的。尽管数组和指针是不同的东西,但前者往往会退化为后者。代码使用它的方式意味着它没有区别。查看更新。
      【解决方案4】:
      if (strcmp(&a[6],b) == 0)
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2020-08-16
        • 1970-01-01
        • 2011-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 2016-07-21
        相关资源
        最近更新 更多