簡體   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