strncmp() in C - Source Code Example

In this source code example, we will see how to use the strncmp() function in C programming with an example.

strncmp() Function Overview

The strncmp() function compares up to the 'n' characters of two strings. It's found in the <string.h> header. If the first 'n' characters of two strings are the same, the function returns 0. If the substring of the first string is less than the second, it returns a negative value. If greater, it returns a positive value. 

 Key points: 

- It's in the <string.h> header. 

- Compares up to 'n' characters of two strings. 

- Can return 0, a negative value, or a positive value.

Source Code Example

#include <stdio.h> #include <string.h> int main() { char string1[] = "applepie"; char string2[] = "applejack"; int n = 5; if (strncmp(string1, string2, n) == 0) { printf("First %d characters of both strings are the same.\n", n); } else if (strncmp(string1, string2, n) < 0) { printf("First %d characters of string1 come before string2 lexicographically.\n", n); } else { printf("First %d characters of string1 come after string2 lexicographically.\n", n); } return 0; } 

Output

First 5 characters of both strings are the same. 

Explanation

1. Two strings are declared: string1 and string2.

2. The strncmp() function is used to compare the first 5 characters.

3. The first 5 characters of both are "apple", so they're the same. The function confirms this with a return value of 0, producing the output.


Comments