C C++中strncmp()和strcmp()的区别
C/C++中strncmp()和strcmp()的基本区别是:
strcmp() 比较两个字符串,直到任一字符串的空字符出现,而 strncmp 最多比较两个字符串的 num 个字符。 但是如果 num 等于任一字符串的长度,则 strncmp 的行为类似于 strcmp。
strcmp() 函数的问题是,如果传入参数的两个字符串都没有以空字符终止,那么字符的比较会继续进行,直到系统崩溃。 但是使用 strncmp 函数,可以限制与 num 参数的比较。
当将 str1 和 str2 作为参数传递给 strcmp() 函数时,它会逐个字符地比较两个字符串,直到 null-character('�') 。 在例子中,直到字符 ‘s’ 两个字符串都保持不变,但之后 str1 的字符 ‘h’ 的 ASCII 值为 104,而 str2 的空字符的 ASCII 值为 0。由于 str1 字符的 ASCII 值大于 ASCII 值 str2 字符,因此 strcmp() 函数返回大于零的值。 因此,字符串 str1 大于 strcmp() 函数中的字符串 str2 。
当在 strncmp() 函数中传递这些参数和第三个参数 num upto 时,它会逐个字符地比较字符串,直到 num(如果 num <= 最小字符串的长度)或直到最小字符串的空字符。 在我们的例子中,两个字符串在 num 之前都具有相同的字符,因此 strncmp() 函数返回值为零。 因此,字符串 str1 等于 strncmp() 函数中的字符串 str2 。
示例代码:
// C, C++ program demonstrate difference between
// strncmp() and strcmp()
#include <stdio.h>
#include <string.h>
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 charactersn");
else if (result1 > 0)
printf("str1 is greater than str2n");
else
printf("str2 is greater than str1n");
printf("Value returned by strncmp() is: %d", result1);
if (result2 == 0)
printf("str1 is equal to str2");
else if (result2 > 0)
printf("str1 is greater than str2");
else
printf("str2 is greater than str1");
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
极客教程