C/C++ difference's between strncmp() and strcmp.

CC++Server Side ProgrammingProgramming

strncmp() and strcmp compares two strings using ASCII character comparison. strncmp takes one additional parameter as number to characters upto which a string is to be compared. It is very useful as if a string is not valid, then strcmp will not be able to complete its operation. strcmp searches for end character ('/0') at string end to finish its operation. strncmp uses no. of characters to end its operation and thus is 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!
raja
Published on 06-Jan-2020 11:05:51
Advertisements