跳轉到內容

C 程式設計/string.h/strcmp

來自華夏公益教科書,自由的教科書

在 POSIX 和 C 程式語言中,strcmp 是 C 標準庫(在 string.h 中宣告)中的一個函式,用於比較兩個 C 字串。

ISO/IEC 9899:1999,7.21.4.2 中的原型

int strcmp(const char *s1, const char *s2);

strcmp 當字串相等時返回 0,當 s1 小於 s2 時返回負整數,或者當 s1 大於 s2 時返回正整數,根據詞典順序。

strcmp 的變體 strncmp 僅比較字串到某個偏移量。

另一個變體 strcasecmp 符合 POSIX.1-2001,工作方式與 strcmp 相同,但區分大小寫。一些系統用名為 stricmpstrcmpi 的函式提供此功能。為了區分大小寫地比較兩個字串的子集,各種系統可能提供 strncasecmpstrnicmpstrncmpi

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char **argv)
{
    int v;

    if (argc < 3)
    {
        fprintf (stderr, "Compares two strings\nUsage: %s string1 string2\n",argv[0]);
        return EXIT_FAILURE;
    }

    v = strcmp (argv[1], argv[2]);

    if (v < 0)
        printf ("'%s' is less than '%s'.\n", argv[1], argv[2]);
    else if (v == 0)
        printf ("'%s' equals '%s'.\n", argv[1], argv[2]);
    else if (v > 0)
        printf ("'%s' is greater than '%s'.\n", argv[1], argv[2]);

    return 0;
}

上面的程式碼是一個工作示例,它列印第一個引數是否小於、等於或大於第二個引數。

一個可能的實現是(P.J. Plauger,The Standard C Library,1992)

int strcmp (const char * s1, const char * s2)
{
    for(; *s1 == *s2; ++s1, ++s2)
        if(*s1 == 0)
            return 0;
    return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}

但是,大多數現實世界的實現將具有各種最佳化技巧來減少函式的執行時間。你會注意到,strcmp 不僅返回 -1、0 和 +1,還返回其他負值或正值,這源於優化了由 ?: 運算子引入的分支。

return *(const unsigned char *)s1 - *(const unsigned char *)s2;
[編輯 | 編輯原始碼]

模板:Compu-prog-stub

華夏公益教科書