Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
What is strncmp() Function in C language?
The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2.
An array of characters is called a string.
Declaration
The syntax for declaring an array is as follows −
char stringname [size];
For example − char string[50]; string of length 50 characters
Initialization
- Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
- Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
The strncmp ( ) Function
This function is used for comparing first ‘n’ characters of 2 strings.
Syntax
The syntax for strncmp() function is as follows −
strncmp ( string1, string2, n)
Example
char a[10] = "the"; char b[10] = "there" strncmp (a,b,3);
The output would be that the Both strings are equal.
Example
Given below is a C program to compare a specific character between two strings using strncmp library function −
#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
When the above program is executed, it produces the following result −
Run1: Enter String 1: Welcome Enter String 2: TO my World Welcome is greater than TO my World Run 2: Enter String 1: welcome Enter String 2: welcome welcome is same as welcome
