Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

C Program to Compare Two Strings Lexicographically

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.


s1 = "geeks", s2 = "geeksforgeeks


String 2 is lexicographically greater than string 1.


 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.



// 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");
        else if (s2[i] > s1[i]) {
            printf("String 2 is lexicographically greater "
                   "than string 1");
    // 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;


String 1 is lexicographically greater than string 2.
  • Time Complexity: O(N)
  • Space complexity: O(1)

My Personal Notes arrow_drop_up
Last Updated : 26 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials