C/C中的strcmp()++

strcmp()是一个内置的库函数,在 头文件。此函数将两个字符串作为参数,并按字典顺序比较这两个字符串。

null

语法: :

int strcmp(const char *leftStr, const char *rightStr );

在上述原型中,函数srtcmp将两个字符串作为参数,并基于字符串的比较返回一个整数值。

  • strcmp()比较 按字典顺序排列的两个字符串 表示从第一个字符开始逐字符比较,直到两个字符串中的字符相等或遇到空字符。
  • 如果两个字符串中的第一个字符相等,则此函数将检查第二个字符,如果第二个字符也相等,则将检查第三个字符,依此类推
  • 此过程将继续,直到任一字符串中的字符为空或字符不相等。

strcmp()返回什么?

此函数可以返回 三个不同的整数值 根据比较:

  1. 零(0) :当发现两个字符串相同时,等于零的值。也就是说,两个字符串中的所有字符都是相同的。
    All characters of strings are same

    // C program to illustrate
    // strcmp() function
    #include<stdio.h>
    #include<string.h>
    int main()
    {
    char leftStr[] = "g f g" ;
    char rightStr[] = "g f g" ;
    // Using strcmp()
    int res = strcmp (leftStr, rightStr);
    if (res==0)
    printf ( "Strings are equal" );
    else
    printf ( "Strings are unequal" );
    printf ( "Value returned by strcmp() is:  %d" , res);
    return 0;
    }

    
    

    输出:

    Strings are equal
    Value returned by strcmp() is:  0
    
  2. 大于零(>0) :如果leftStr中的第一个不匹配字符的ASCII值大于rightStr中的相应字符,则返回大于零的值,或者我们也可以说
    If character in leftStr is lexicographically
    after the character of rightStr 

    // C program to illustrate
    // strcmp() function
    #include<stdio.h>
    #include<string.h>
    int main()
    {
    // z has greater ASCII value than g
    char leftStr[] = "zfz" ;
    char rightStr[] = "gfg" ;
    int res = strcmp (leftStr, rightStr);
    if (res==0)
    printf ( "Strings are equal" );
    else
    printf ( "Strings are unequal" );
    printf ( "Value of result: %d" , res);
    return 0;
    }

    
    

    输出:

    Strings are unequal
    Value returned by strcmp() is:  19
    
  3. 小于零(<0) :当leftStr中的第一个不匹配字符的ASCII值小于rightStr中的对应字符时,返回小于零的值。
    If character in leftStr is lexicographically
    before the character of rightStr

    // C program to illustrate
    // strcmp() function
    #include<stdio.h>
    #include<string.h>
    int main()
    {
    // b has less ASCII value than g
    char leftStr[] = "bfb" ;
    char rightStr[] = "gfg" ;
    int res = strcmp (leftStr, rightStr);
    if (res==0)
    printf ( "Strings are equal" );
    else
    printf ( "Strings are unequal" );
    printf ( "Value returned by strcmp() is:  %d" , res);
    return 0;
    }

    
    

    输出:

    Strings are unequal
    Value returned by strcmp() is:  -5
    

    要点: 当字符串不相同时,您会发现strcmp()函数返回的值是leftStr和rightStr中第一个不匹配字符的ASCII值之间的差异。 本文由 严酷的阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

    如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享