C++

How Can I Compare Two Strings in C++?

Strings are created in two main ways in C++: using a constant pointer or instantiating from a string class. The string literal, “I have discovered treasure.” can be constructed in the following ways in C++:

char str1[] = "I have discovered treasure.";

const char* str2 = "I have discovered treasure.";

#include <string>

string str3 = string("I have discovered treasure.");

string str4 = string("I have discovered treasure.");

Creating a string using an array or the constant character pointer, are the same way of creating a string. str3 and str4 here have been created by instantiation from the included string library. Note that the double quotes used by string literals in programming are not the same as the ones used by a word processor.

The question is, “How can I compare two Strings in C++?” The first advice is that do not compare strings created by constant character pointers. When you do that, you are comparing the pointers and not the string literal. So, do no compare str1 and str2 above. If you do that, you are comparing their pointers and not their contents.

To compare strings in C++, you have to compare the strings created by instantiation of the included string library. So str3 and str4 above can be compared, and they will compare equal.

This tutorial explains how to compare string literals in C++, beginning with the comparison of characters in C++. The comparison of characters leads to the comparison of strings, though characters are treated differently from strings, in C++.

Article Content

Comparison of Characters

Characters are actually represented in the computer by numbers. So, when comparing characters, it is the numbers that are compared.

The order for comparing characters, which form string literals, is as follows: digits come first before uppercase letters, which come before lowercase letters. Other characters such as the bell, the tab, the Enter key, the $, the &, the [, the backslash, the {, the |, and the }, are placed before or after, or at the intervals of these ranges. Comparing characters in C++ uses relational and equality operators which are:

< meaning, less than

> meaning, greater than

<= meaning, less than or equal to

>= meaning, greater than or equal to

== meaning, equal to

!= meaning, not equal to

The string class also uses these operators to compare string literals.

Note: A character is single and it is delimited by single quotes.

Each of the following two statements prints 1, for true:

        cout << ('5' < 'E') << endl;

cout << ('E' < 'e') << endl;

Each of the following two statements prints, 1 for true:

cout << ('E' <= 'E') << endl;

cout << ('E' >= 'E') << endl;

The following statement prints 1, for true:

cout << ('e' == 'e') << endl;

The following statement prints 1, for true:

cout << ('e' != 'E') << endl;

String Class Objects

After including the string library with the include-directive, a string object can be instantiated (constructed) in C++, in the following ways:

string str = "How come? - $50,000!";

string str = string("How come? - $50,000!");

string str = string({'H','o','w',' ','c','o','m','e','?',' ','-',' ','$','5','0',',','0','0','0','!','\0'});

The string literal for these three cases are the same. However, note the NUL character ‘\0’, at the end of the array content.

Already, there are six non-alphabetic characters in this string literal, which are ‘?’, ‘$’, ‘-’ , ‘,’, ‘!’ and the space (‘ ’). Imagine a new dictionary, where non-alphabetic characters are used in words, and respects the order (ASCII) mentioned above. You already know how to compare words in the normal dictionary. C++ compares string literals in that same way in this new dictionary.

Remember, to compare string literals in C++, compare the string objects represented by their identifiers.

Equality Operation

The equal-to operator is, == . The syntax is:

strA == strB

If the content of strA is the same as the content of strB, respecting casing (not ignoring capital and small letters), then the result of the operation is true.

The not-equal-to operator is, != . The syntax is:

strA != strB

The slightest difference in content, between strA and strB, respecting casing (not ignoring capital and small letters), results in false, for this operation.

Consider the following code:

string str1 = "$moneyA[26]";

string str2 = "$moneyA[26]";

bool blA = str1 == str2;

cout << blA << endl;

 

string str3 = "$moneyA[26]";

string str4 = "$MONEYA[26]";

bool blB = str3 == str4;

cout << blB << endl;

The output is:

1    //for true

0    //for false

The sequences are the same for str1 and str2 literals; so, the return value is true. The sequences are like the same for str3 and str4 literals; but one string literal has lowercase text and the other has uppercase text; so, the return value is false.

The following is the above code repeated, but with “!=” instead of “==”.

string str1 = "$moneyA[26]";

string str2 = "$moneyA[26]";

bool blA = str1 != str2;

cout << blA << endl;

 

string str3 = "$moneyA[26]";

string str4 = "$MONEYA[26]";

bool blB = str3 != str4;

cout << blB << endl;

The output is:

0    //for false

1    //for true

Ignoring Case in Comparison

As of now, C++ does not have a function to compare strings, ignoring case. The way to do this is to convert both strings to uppercase, before comparing. The algorithm library will have to be included. This library has the transform() function, which does conversion to uppercase. For the statement,

string str = "I love $1000 US.";

The construct,

transform(str.begin(), str.end(), str.begin(), ::toupper);

Will turn the literal represented by str, to:

"I LOVE $1000 US."

Note that non-alphabetic characters, such as ‘$’, ‘.’ and the space did not change (because they do not have upper and lowercase variants).

The following program uses this scheme, to compare string literals, ignoring case:

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

  string str3 = "$moneyA[26]";

  transform(str3.begin(), str3.end(), str3.begin(), ::toupper);

  string str4 = "$MONEYA[26]";

  transform(str4.begin(), str4.end(), str4.begin(), ::toupper);

  bool blB = str3 == str4;

  cout << blB << endl;

  return 0;

}

The output is 1, for true, since both strings are now in uppercase, every other thing being equal.

Less Than, Greater Than

strA < strB

Results in true, if the literal of strA would appear in the dictionary, before that of strB.

    strA > strB

Results in true, if the literal of strA would appear in the dictionary, after that of strB.

The following code returns true, because “WXYZ” is less than “wxyz”:

string str1 = "WXYZ";

string str2 = "wxyz";

bool bl = str1 < str2;

cout << bl << endl;

The output is 1. The following code returns true, because “stuv” is less than “wxyz”:

string str1 = "stuv";

string str2 = "wxyz";

bool bl = str1 < str2;

cout << bl << endl;

The output is 1, for true. The following code returns false, because “wxyz” is equal to “wxyz”, and str1 is not less than str2.

string str1 = "wxyz";

string str2 = "wxyz";

bool bl = str1 < str2;

cout << bl << endl;

The output is 0. The following code returns true, because “wxy” is greater than “bcde”:

string str1 = "wxy";

string str2 = "bcde";

bool bl = str1 > str2;

cout << bl << endl;

The output is 1.

Less Than or Equal To, Greater Than or Equal To

 strA <= strB

Results in true, if the literal of strA is less than, or happen to be the same (equal to) as that of strB.

strA > =strB

Results in true, if the literal of strA is greater than, or happen to be the same (equal to) as that of strB.

The following code returns true, because “WXYZ” is less than or equal to “wxyz”:

string str1 = "WXYZ";

string str2 = "wxyz";

bool bl = str1 <= str2;

cout << bl << endl;

The output is 1. The following code returns true, because “stuv” is less than or equal to “wxyz”:

string str1 = "stuv";

string str2 = "wxyz";

bool bl = str1 <= str2;

cout << bl << endl;

The output is 1. The following code returns true, because “wxyz” is less than or equal to “wxyz” (and str1 is not less than str2).

string str1 = "wxyz";

string str2 = "wxyz";

bool bl = str1 <= str2;

cout << bl << endl;

The output is 1. The following code returns true, because “wxy” is greater than or equal to “bcde”:

string str1 = "wxy";

string str2 = "bcde";

bool bl = str1 >= str2;

cout << bl << endl;

The output is 1.

Conclusion

To compare characters in C++, use the equality and relational operators. To compare string literals, still use the equality and relational operators, but for objects of the string class, and not for const char*s. Using the operators for const char*s compares the pointers, and not the string literals.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.