Home  >  Article  >  Backend Development  >  C/C++ difference between strncmp() and strcmp()

C/C++ difference between strncmp() and strcmp()

王林
王林forward
2023-09-02 18:21:07700browse

C/C++ difference between strncmp() and strcmp()

strncmp() and strcmp use ASCII character comparison to compare two strings. strncmp takes an additional argument as the number of characters to compare with the string. It's useful because strcmp won't be able to complete its operation if the string is invalid. strcmp searches for a terminating character ('/0') at the end of the string to complete its operation. strncmp uses no. character to end its operation and is therefore safe.

Example

#include <stdio.h>
int main() {
   char str1[] = "TutorialsPoint";
   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;
}

Output

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

The above is the detailed content of C/C++ difference between strncmp() and strcmp(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete