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

strncmp()和strcmp使用ASCII字符比较来比较两个字符串。strncmp将一个附加参数用作要比较的字符串的数字。如果字符串无效,这很有用,那么strcmp将无法完成其操作。strcmp在字符串结尾搜索结束字符('/ 0')以完成其操作。strncmp使用否。字符结束操作,因此是安全的。

示例

#include <stdio.h>
int main() {
   char str1[] = "nhooo";
   char str2[] = "Tutorials";
   // Compare strings with strncmp()   int result1 = strncmp(str1, str2, 9);
   if(result1 == 0){
      printf("str1 == str2 upto 9 characters!\n");
   }
   // Compare strings using strcmp()   int result2 = strcmp(str1, str2);
   if(result2 == 0){
      printf("str1 == str2!\n");
   } else {
      if(result2 > 0){
         printf("str1 > str2!\n");
      } else {
         printf("str1 < str2!\n");
      }
   }
   return 0;
}

输出结果

str1 == str2 upto 9 characters!
str1 > str2!