📜  C / C++中的strncmp()和strcmp之间的区别

📅  最后修改于: 2021-05-26 00:10:28             🧑  作者: Mango

先决条件:strncmp,strcmp

两者之间的基本区别是:

  1. STRCMP比较两个字符串,直到要么字符串的空字符来,而strncmp对在两个字符串的最NUM个字符。但是,如果num等于任一字符串的长度,则strncmp的行为类似于strcmp
  2. strcmp函数的问题在于,如果在参数中传递的两个字符串都没有以null字符终止,则继续比较字符,直到系统崩溃为止。但是使用strncmp函数,我们可以将比较限制为num参数。

当通str1和STR2作为参数对strcmp()函数,它两个字符串逐个,直到空字符(“\ 0”)进行比较。在我们的示例中,两个字符的字符串保持字符s不变,但之后str1的字符‘h’的ASCII值为104,而str2的空字符的ASCII值为0。由于str1字符的ASCII值大于ASCII值是str2字符,因此strcmp()函数返回的值大于零。因此,在strcmp()函数,字符串str1大于字符串str2。
当通过在STRNCMP这些参数()与所述第三参数NUM高达其要比较字符串函数则两个字符串逐个NUM直到比较(如果num <=最小字符串的长度)或直到最小字符串的空字符。在我们的例子中,两个字符串在num之前都具有相同的字符,因此strncmp()函数返回零值。因此,字符串str1等于strncmp()函数的字符串str2。

// C, C++ program demonstrate difference between
// strncmp() and strcmp()
#include 
#include 
  
int main()
{
    // Take any two strings
    char str1[] = "akash";
    char str2[] = "akas";
  
    // Compare strings using strncmp()
    int result1 = strncmp(str1, str2, 4);
  
    // Compare strings using strcmp()
    int result2 = strcmp(str1, str2);
  
    // num is the 3rd parameter of strncmp() function 
    if (result1 == 0)         
        printf("str1 is equal to str2 upto num characters\n");    
    else if (result1 > 0)
        printf("str1 is greater than str2\n");
    else
        printf("str2 is greater than str1\n");
  
    printf("Value returned by strncmp() is: %d\n", result1);
  
    if (result2 == 0) 
        printf("str1 is equal to str2\n");    
    else if (result2 > 0)
        printf("str1 is greater than str2\n");
    else
        printf("str2 is greater than str1\n");
  
    printf("Value returned by strcmp() is: %d", result2);
  
    return 0;
}

输出:

str1 is equal to str2 upto num characters
Value returned by strncmp() is: 0
str1 is greater than str2
Value returned by strcmp() is: 104
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。