繁体   English   中英

在字符串的子集上使用strcmp

[英]Using strcmp on a subset of a string

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

说我有:

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

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

我想第二个字比较a与整个字符串b 我知道第二个字的起始索引a 有没有办法做到这一点直接使用strcmp或做更多的字a首先需要做什么?

abchar数组,但它们不是字符串,因为它们不是以null结尾的。

如果将它们修改为以null终止,如下所示:

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)进行比较。

if (strcmp((a + index), b) == 0) { ... }

strcmp需要两个指针,因此您可以直接添加索引。

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

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

您对世界上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...调用不是真正适合使用的调用。

if (strcmp(&a[6],b) == 0)

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM