Comparing Strings in C++

String comparison is a fundamental operation in programming, especially in C++. Whether you are checking user input, validating passwords, sorting text, or implementing algorithms that rely on string ordering, understanding how to compare strings correctly is essential.

C++ provides multiple ways to compare strings depending on whether you are using C++ standard library strings (std::string) or C-style strings (character arrays). In this post, we will explore the various methods of comparing strings, the operators involved, the compare() function, and practical examples, including password checks and dictionary ordering.

Overview of String Comparison

Comparing strings generally involves checking one of the following conditions:

  1. Equality – whether two strings are identical.
  2. Inequality – whether two strings are different.
  3. Lexicographical Order – whether one string comes before or after another string in dictionary order.

The method you choose depends on the type of string you are using and the type of comparison required.


Comparing C++ Strings Using Operators

The C++ Standard Library provides the std::string class, which supports relational operators for comparison. These operators make string comparison straightforward and readable.

Operators for Comparing std::string

  • == : Checks if two strings are equal.
  • != : Checks if two strings are not equal.
  • < : Checks if the first string comes before the second string in lexicographical order.
  • > : Checks if the first string comes after the second string in lexicographical order.
  • <= : Checks if the first string comes before or is equal to the second string.
  • >= : Checks if the first string comes after or is equal to the second string.

Example: Using Operators

#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "Apple";
string str2 = "Banana";
if (str1 == str2) {
    cout &lt;&lt; "Strings are equal." &lt;&lt; endl;
} else {
    cout &lt;&lt; "Strings are not equal." &lt;&lt; endl;
}
if (str1 &lt; str2) {
    cout &lt;&lt; str1 &lt;&lt; " comes before " &lt;&lt; str2 &lt;&lt; " in dictionary order." &lt;&lt; endl;
} else {
    cout &lt;&lt; str1 &lt;&lt; " comes after " &lt;&lt; str2 &lt;&lt; " in dictionary order." &lt;&lt; endl;
}
return 0;
}

Output:

Strings are not equal.
Apple comes before Banana in dictionary order.

Explanation:

  • The == operator checks equality and returns false because "Apple" is not equal to "Banana".
  • The < operator performs a lexicographical comparison, which is similar to dictionary order. "Apple" comes before "Banana".

Using the compare() Function

The std::string class also provides a compare() method, which is useful for comparing strings. This function returns an integer value indicating the relationship between the strings.

Syntax

int result = str1.compare(str2);

Where:

  • If result == 0, str1 and str2 are equal.
  • If result < 0, str1 comes before str2.
  • If result > 0, str1 comes after str2.

Example: Using compare()

#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "Apple";
string str2 = "Banana";
int result = str1.compare(str2);
if (result == 0) {
    cout &lt;&lt; "Strings are equal." &lt;&lt; endl;
} else if (result &lt; 0) {
    cout &lt;&lt; str1 &lt;&lt; " comes before " &lt;&lt; str2 &lt;&lt; endl;
} else {
    cout &lt;&lt; str1 &lt;&lt; " comes after " &lt;&lt; str2 &lt;&lt; endl;
}
return 0;
}

Output:

Apple comes before Banana

Advantages of compare():

  • It provides more control when performing string comparison.
  • You can compare substrings by specifying start positions and lengths.
  • It can be used to perform case-sensitive or case-insensitive comparisons with additional manipulation.

Comparing C-style Strings Using strcmp()

When working with C-style strings (character arrays), operators like == or < do not work as expected. Instead, you need to use the strcmp() function from the <cstring> library.

Syntax

int result = strcmp(str1, str2);

Where:

  • str1 and str2 are null-terminated character arrays.
  • Returns 0 if strings are equal.
  • Returns a negative value if str1 comes before str2.
  • Returns a positive value if str1 comes after str2.

Example: Using strcmp()

#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1&#91;] = "Apple";
char str2&#91;] = "Banana";
int result = strcmp(str1, str2);
if (result == 0) {
    cout &lt;&lt; "Strings are equal." &lt;&lt; endl;
} else if (result &lt; 0) {
    cout &lt;&lt; str1 &lt;&lt; " comes before " &lt;&lt; str2 &lt;&lt; endl;
} else {
    cout &lt;&lt; str1 &lt;&lt; " comes after " &lt;&lt; str2 &lt;&lt; endl;
}
return 0;
}

Output:

Apple comes before Banana

Explanation:

  • strcmp() compares the strings character by character.
  • The return value indicates the lexicographical relationship between the strings.

Comparing Strings for Equality

Using == with std::string

Checking for equality is common, such as when verifying user credentials or input.

#include <iostream>
#include <string>
using namespace std;

int main() {
string password = "Secret123";
string input;
cout &lt;&lt; "Enter password: ";
cin &gt;&gt; input;
if (input == password) {
    cout &lt;&lt; "Access granted." &lt;&lt; endl;
} else {
    cout &lt;&lt; "Access denied." &lt;&lt; endl;
}
return 0;
}

Explanation:

  • The == operator directly compares two std::string objects.
  • If the strings are identical, access is granted.

Using strcmp() with C-style Strings

For C-style strings, equality checking must use strcmp():

#include <iostream>
#include <cstring>
using namespace std;

int main() {
char password&#91;] = "Secret123";
char input&#91;20];
cout &lt;&lt; "Enter password: ";
cin &gt;&gt; input;
if (strcmp(input, password) == 0) {
    cout &lt;&lt; "Access granted." &lt;&lt; endl;
} else {
    cout &lt;&lt; "Access denied." &lt;&lt; endl;
}
return 0;
}

Explanation:

  • strcmp() returns 0 if the input matches the password exactly.

Comparing Strings for Lexicographical Order

Lexicographical comparison is the method of comparing strings based on dictionary order. It is essential for tasks such as sorting words or checking relative positions.

Using < and > with std::string

#include <iostream>
#include <string>
using namespace std;

int main() {
string word1 = "Apple";
string word2 = "Banana";
if (word1 &lt; word2) {
    cout &lt;&lt; word1 &lt;&lt; " comes before " &lt;&lt; word2 &lt;&lt; endl;
} else {
    cout &lt;&lt; word1 &lt;&lt; " comes after " &lt;&lt; word2 &lt;&lt; endl;
}
return 0;
}

Output:

Apple comes before Banana

Using strcmp() for C-style Strings

#include <iostream>
#include <cstring>
using namespace std;

int main() {
char word1&#91;] = "Apple";
char word2&#91;] = "Banana";
if (strcmp(word1, word2) &lt; 0) {
    cout &lt;&lt; word1 &lt;&lt; " comes before " &lt;&lt; word2 &lt;&lt; endl;
} else {
    cout &lt;&lt; word1 &lt;&lt; " comes after " &lt;&lt; word2 &lt;&lt; endl;
}
return 0;
}

Explanation:

  • strcmp() provides a return value that helps determine order:
    • Negative: first string is less than the second
    • Zero: strings are equal
    • Positive: first string is greater than the second

Case Sensitivity in String Comparison

By default, string comparison is case-sensitive in C++. This means that "apple" and "Apple" are considered different strings.

Example: Case-Sensitive Comparison

#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "apple";
string str2 = "Apple";
if (str1 == str2) {
    cout &lt;&lt; "Strings are equal." &lt;&lt; endl;
} else {
    cout &lt;&lt; "Strings are not equal." &lt;&lt; endl;
}
return 0;
}

Output:

Strings are not equal.

Solution for Case-Insensitive Comparison:

  • Convert both strings to lowercase or uppercase before comparison using transform() from <algorithm>:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
string str1 = "apple";
string str2 = "Apple";
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
transform(str2.begin(), str2.end(), str2.begin(), ::tolower);
if (str1 == str2) {
    cout &lt;&lt; "Strings are equal (case-insensitive)." &lt;&lt; endl;
} else {
    cout &lt;&lt; "Strings are not equal." &lt;&lt; endl;
}
return 0;
}

Output:

Strings are equal (case-insensitive).

Comparing Substrings

Sometimes you may want to compare only a portion of a string. The std::string::compare() function allows you to specify substrings to compare.

Example: Comparing Substrings

#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "HelloWorld";
string str2 = "Hello";
if (str1.compare(0, 5, str2) == 0) {  // Compare first 5 characters
    cout &lt;&lt; "The first part of str1 matches str2." &lt;&lt; endl;
} else {
    cout &lt;&lt; "They do not match." &lt;&lt; endl;
}
return 0;
}

Output:

The first part of str1 matches str2.

Practical Example: Checking Passwords

String comparison is frequently used in authentication systems. Here’s an example of comparing a password entered by the user:

#include <iostream>
#include <string>
using namespace std;

int main() {
string password = "MyPassword123";
string input;
cout &lt;&lt; "Enter password: ";
cin &gt;&gt; input;
if (input == password) {
    cout &lt;&lt; "Login successful." &lt;&lt; endl;
} else {
    cout &lt;&lt; "Incorrect password." &lt;&lt; endl;
}
return 0;
}

Explanation:

  • The program reads the user’s input and compares it with the stored password using the == operator.

Practical Example: Dictionary Order

Comparing strings lexicographically is useful in sorting words, such as for a dictionary or alphabetical order:

#include <iostream>
#include <string>
using namespace std;

int main() {
string word1 = "Banana";
string word2 = "Apple";
if (word1 &lt; word2) {
    cout &lt;&lt; word1 &lt;&lt; " comes before " &lt;&lt; word2 &lt;&lt; endl;
} else {
    cout &lt;&lt; word1 &lt;&lt; " comes after " &lt;&lt; word2 &lt;&lt; endl;
}
return 0;
}

Output:

Banana comes after Apple

Best Practices for Comparing Strings

  1. Prefer std::string over C-style strings for ease of use and safety.
  2. Use compare() when you need return codes for more complex comparisons.
  3. Use == or != for simple equality checks.
  4. Convert strings to a common case for case-insensitive comparisons.
  5. Use strcmp() only for C-style strings.
  6. Use substrings carefully to avoid out-of-bounds errors.

Comments

Leave a Reply

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