C Program to Compare Two Strings Lexicographically
Last Updated :
26 Jul, 2022
Here, we will build a C Program to compare two strings lexicographically. Given 2 strings s1 and s2, of lowercase English alphabets, denote the lexicographically greater string. Lexicographical order is the order in which words appear in the order of a dictionary.
Input:
s1 = "geeks", s2 = "geeksforgeeks
Output:
String 2 is lexicographically greater than string 1.
Approach
Sequence to follow these steps:
- Iterate over both the strings using a for-loop.
- Compare each character of the two strings till an unmatched character is found.
- For the unmatched character at position i, if s1[i] < s2[i], s1 is lexicographically smaller string.
- Otherwise, s2 is the lexicographically smaller string.
- If no unmatched character is found, compare the length of both strings.
- The longer string is lexicographically smaller.
Example:
C
#include <stdio.h>
void compareStrings( char * s1, char * s2)
{
int i;
for (i = 0; s1[i] != '\0' || s2[i] != '\0' ; i++) {
if (s1[i] > s2[i]) {
printf ( "String 1 is lexicographically greater "
"than string 2" );
return ;
}
else if (s2[i] > s1[i]) {
printf ( "String 2 is lexicographically greater "
"than string 1" );
return ;
}
}
if (s1[i] != '\0' ) {
printf ( "String 1 is lexicographically greater than "
"string 2" );
}
else if (s2[i] != '\0' ) {
printf ( "String 2 is lexicographically greater than "
"string 1" );
}
else {
printf ( "Both strings are lexicographically equal" );
}
}
int main()
{
char s1[20] = "help" ;
char s2[20] = "held" ;
compareStrings(s1, s2);
return 0;
}
|
Output:
String 1 is lexicographically greater than string 2.
- Time Complexity: O(N)
- Space complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...