Compare Strings alphabetically in C++

This tutorial will discuss about a unique way to compare strings alphabetically in C++.

Suppose we have two strings now we want to compare them alphabetically. For example, strings are,

std::string firstStr = "Testing";
std::string secondStr = "Tested";

Here, “Tested” comes before “Testing” alphabetically. It is because the first 4 characters in both the strings are exactly equal, but the for the fift the character, ASCI value of letter ‘e’ is smaller than letter ‘i’.

By comparing two strings alphabetically we mean,
* If both the strings are exactly equal, if they contains exactly equal characters in equal order then they should be alphabetically equal.
* If both the strings has different values, then we need to check if first string is smaller than the second string alphabetically. For that, we will compare each characters of both the strings alphabetically based on ASCII values.

We can use the < or > operators on the string objects to check if first value is less than second value in alphabetical order.

Let’s see the complete example,

#include <iostream>
#include <string>

int main()
{
    std::string firstStr = "Testing";
    std::string secondStr = "Tested";


    // Compare two strings alphabetically
    if (firstStr < secondStr)
    {
        // If first string is lesser than second string alphabetically
        std::cout << "\"" << firstStr << "\" comes before \"" << secondStr << "\" alphabetically." << std::endl;
    }
    else if (firstStr > secondStr)
    {
        // If second string is lesser than first string alphabetically
        std::cout << "\"" << secondStr << "\" comes before \"" << firstStr << "\" alphabetically." << std::endl;
    }
    else
    {
        // If first and second strings are equal alphabetically
        std::cout << "\"" << firstStr << "\" and \"" << secondStr << "\" are equal alphabetically." << std::endl;
    }

    return 0;
}

Output :

"Tested" comes before "Testing" alphabetically.

Summary

Today we learned about several ways to compare strings alphabetically in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top