![]() |
VOOZH | about |
In C, lexicographic comparison refers to comparing each character of one string to the character of other string at same position based on their alphabetical order, just like how words are arranged in a dictionary. In this article, we will learn how to compare two strings lexicographically using the C program.
The most straightforward method to compare two strings lexicographically is by using strcmp() function. Let's take a look at an example:
"Geeks" is lexicographically smaller than "gfg".
Explanation: The strncmp() function returns 0 if two strings are equal. If s1 is greater than s2, it returns positive value. If s1 is less than s2, it returns negative value.
There are also a few other methods in C to compare two strings lexicographically. Some of them are as follows:
The strncmp() compares first n characters of the given two strings in the same ways as strcmp() function.
"Geeks" is smaller than"gfg".
Explanation: We took the length of the smaller string as the characters to be compared.
This method compares characters of both strings in a loop until a mismatch is found or one string ends. If one string is shorter but matches entirely, it is smaller. If no mismatch occurs and lengths are equal, the strings are equal.
"Hello" lexicographically greater than "Geeks".