The function strncmp () in C

The function int strncmp (const char * str1, const char * str2, size_t n) compares the first n bytes of str1 and str2.

Declaring the function strncmp () in C

Below is the declaration for strncmp () in C:

 int strncmp ( const char * str1 , const char * str2 , size_t n ) 

Parameters

str1 - This is the first string to be compared.

str2 - This is the second string to be compared.

n - Maximum number of characters to be compared.

Returns the value

This function returns the following values:

If the value returns <0, this function indicates that str1 is shorter than str2.

If the value returns> 0, this function indicates that str2 is shorter than str1.

If the return value = 0, this function indicates that str1 is equal to str2.

For example

The following C program illustrates the usage of strncmp () in C:

 #include #include int main () { char str1 [ 15 ]; char str2 [ 15 ]; int ret ; strcpy ( str1 , "abcdef" ); strcpy ( str2 , "ABCDEF" ); ret = strncmp ( str1 , str2 , 4 ); if ( ret < 0 ) { printf ( "Chuoi str1 la ngan hon chuoi str2" ); } else if ( ret > 0 ) { printf ( "Chuoi str2 la ngan hon chuoi str1" ); } else { printf ( "Chuoi str1 la bang chuoi str2" ); } return ( 0 ); } 

Compiling and running the above C program will result:

The function strncmp () in C Picture 1

According to Tutorialspoint

Previous article: Function strcmp () in C

Next lesson: strcoll () function in C

5 ★ | 1 Vote

May be interested

  • The strcoll () function in CPhoto of The strcoll () function in C
    the function int strcoll (const char * str1, const char * str2) compares strings str1 and str2. the result depends on setting lc_collate.
  • Strcpy () function in CPhoto of Strcpy () function in C
    char * strcpy function (char * dest, const char * src) copies the string pointed to by src to dest.
  • The strncpy () function in CPhoto of The strncpy () function in C
    strncpy char * (char * dest, const char * src, size_t n) copies up to n copies to n characters from the string pointed to by src to dest. in case the length of the src is smaller than n, the remainder or the remainder of dest will be filled with null values.
  • The strcspn () function in CPhoto of The strcspn () function in C
    the function size_t strcspn (const char * str1, const char * str2) calculates the length of the character segment of string str1 without containing the characters in str2.
  • The strerror () function in CPhoto of The strerror () function in C
    the function char * strerror (int errnum) searches for an internal array for errnum error numbers and returns a pointer to a string of error messages.
  • The strlen () function in CPhoto of The strlen () function in C
    the function size_t strlen (const char * str) calculates the length of str string (not including the ending null character).