Home >Backend Development >C++ >Write a C program that uses the strncmp library function to compare two strings

Write a C program that uses the strncmp library function to compare two strings

WBOY
WBOYforward
2023-09-09 13:17:01782browse

Strncmp is a predefined library function that exists in the string.h file. It is used to compare two strings and display which string is larger.

strcmp function (string comparison)

This function compares two strings. It returns the ASCII difference of the first non-matching character in the two strings.

Syntax

int strcmp (string1, string2);
  • If the difference is equal to zero, then string1 = string2.

  • If the difference is positive, string1> string2.

  • If the difference is negative, string1

Example

Write a C program that uses the strncmp library function to compare two strings

strncmp function

This function is used to compare the first n characters of two strings .

Syntax

strncmp ( string1, string2,2)

Program

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring two strings//
   char string1[25],string2[25];
   int value;
   //Reading string 1 and String 2//
   printf("Enter String 1: ");
   gets(string1);
   printf("Enter String 2: ");
   gets(string2);
   //Comparing using library function//
   value = strncmp(string1,string2,4);
   //If conditions//
   if(value==0){
      printf("%s is same as %s",string1,string2);
   } else if(value>0) {
      printf("%s is greater than %s",string1,string2);
   } else {
      printf("%s is less than %s",string1,string2);
   }
}

Output

Enter String 1: Tutorials
Enter String 2: Point
Tutorials is greater than Point

The above is the detailed content of Write a C program that uses the strncmp library function to compare two strings. 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