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:
- Equality – whether two strings are identical.
- Inequality – whether two strings are different.
- 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 << "Strings are equal." << endl;
} else {
cout << "Strings are not equal." << endl;
}
if (str1 < str2) {
cout << str1 << " comes before " << str2 << " in dictionary order." << endl;
} else {
cout << str1 << " comes after " << str2 << " in dictionary order." << 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
andstr2
are equal. - If
result < 0
,str1
comes beforestr2
. - If
result > 0
,str1
comes afterstr2
.
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 << "Strings are equal." << endl;
} else if (result < 0) {
cout << str1 << " comes before " << str2 << endl;
} else {
cout << str1 << " comes after " << str2 << 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
andstr2
are null-terminated character arrays.- Returns
0
if strings are equal. - Returns a negative value if
str1
comes beforestr2
. - Returns a positive value if
str1
comes afterstr2
.
Example: Using strcmp()
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2);
if (result == 0) {
cout << "Strings are equal." << endl;
} else if (result < 0) {
cout << str1 << " comes before " << str2 << endl;
} else {
cout << str1 << " comes after " << str2 << 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 << "Enter password: ";
cin >> input;
if (input == password) {
cout << "Access granted." << endl;
} else {
cout << "Access denied." << endl;
}
return 0;
}
Explanation:
- The
==
operator directly compares twostd::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[] = "Secret123";
char input[20];
cout << "Enter password: ";
cin >> input;
if (strcmp(input, password) == 0) {
cout << "Access granted." << endl;
} else {
cout << "Access denied." << endl;
}
return 0;
}
Explanation:
strcmp()
returns0
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 < word2) {
cout << word1 << " comes before " << word2 << endl;
} else {
cout << word1 << " comes after " << word2 << 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[] = "Apple";
char word2[] = "Banana";
if (strcmp(word1, word2) < 0) {
cout << word1 << " comes before " << word2 << endl;
} else {
cout << word1 << " comes after " << word2 << 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 << "Strings are equal." << endl;
} else {
cout << "Strings are not equal." << 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 << "Strings are equal (case-insensitive)." << endl;
} else {
cout << "Strings are not equal." << 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 << "The first part of str1 matches str2." << endl;
} else {
cout << "They do not match." << 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 << "Enter password: ";
cin >> input;
if (input == password) {
cout << "Login successful." << endl;
} else {
cout << "Incorrect password." << 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 < word2) {
cout << word1 << " comes before " << word2 << endl;
} else {
cout << word1 << " comes after " << word2 << endl;
}
return 0;
}
Output:
Banana comes after Apple
Best Practices for Comparing Strings
- Prefer
std::string
over C-style strings for ease of use and safety. - Use
compare()
when you need return codes for more complex comparisons. - Use
==
or!=
for simple equality checks. - Convert strings to a common case for case-insensitive comparisons.
- Use
strcmp()
only for C-style strings. - Use substrings carefully to avoid out-of-bounds errors.
Leave a Reply