C strncmp() Function

You are Here:

C strncmp() Function

The strncmp() function compares the characters of two strings up to the specified length.

The characters of the strings may be in lower case or upper case, this function discriminates between them.

Every character holds an ASCII value (an integer ranging from 0 to 127). For example, 'A' holds the ASCII value of 65 and 'a' holds the ASCII value of 97. So, in the comparison between two strings, their ASCII values are compared.

The strncmp() function starts comparison character by character starting from the first character until the characters in both strings are equal, reached the specified length, or a NULL character is encountered.

Example

C Compiler
#include <stdio.h> #include <string.h> int main() { const char str1[] = "abcd"; const char str2[] = "abcdABCD"; int res = strncmp(str1, str2, 4); if(res == 0) printf("str1 is equal to str2"); else if(res > 0) printf("str1 is greater than str2"); else printf("str1 is less than str2"); return 0; }

Output

str1 is equal to str2

Syntax

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

Parameter Values

ValueTypeExplanation
str1RequiredSpecifies the string 1
str2RequiredSpecifies the string 2
nRequiredSpecifies the length up to which the characters in the strings are compared.

Return Value

This function returns the numeric difference between the ASCII values of non-matching characters.

ValueExplanation
+iveIf str1 is greater than str2
0If str1 is equal to str2
-iveIf str1 is less than str2

Reminder

Hi Developers, we almost covered 98% of String functions and Interview Question on C with examples for quick and easy learning.

We are working to cover every Single Concept in C.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author