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

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

王林
Release: 2023-09-02 18:21:07
forward
923 people have browsed it

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;
}
Copy after login

Output

str1 == str2 upto 9 characters!
str1 > str2!
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template