Open In App

C Program to Compare Two Strings Lexicographically

Last Updated : 26 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Iterate over both the strings using a for-loop.
  2. Compare each character of the two strings till an unmatched character is found.
  3. For the unmatched character at position i, if s1[i] < s2[i], s1 is lexicographically smaller string.
  4. Otherwise, s2 is the lexicographically smaller string.
  5. If no unmatched character is found, compare the length of both strings.
  6. The longer string is lexicographically smaller.

Example:

C




// C program to demonstrate arranging
// strings lexicographically
#include <stdio.h>
  
void compareStrings(char* s1, char* s2)
{
    int i;
    // comparing each character
    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;
        }
    }
    // comparing length of two strings
    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()
{
  
    // declaring two strings
    char s1[20] = "help";
    char s2[20] = "held";
  
    // function call
    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
Previous
Next
Share your thoughts in the comments

Similar Reads