In C++, comparing strings is a common task that can be accomplished using several methods depending on the context and string type. You might need to compare strings for equality, lexicographical order, or to determine which string is greater or lesser.
strcmp Function
The strcmp function, found in the <cstring> library, compares two C-style strings (null-terminated character arrays). It returns:
0 if the strings are equal.
Example:
#include <cstring>
#include <iostream>
int main() {
const char* str1 = "Hello";
const char* str2 = "World";
if (strcmp(str1, str2) == 0) {
std::cout << "Strings are equal";
} else {
std::cout << "Strings are not equal";
}
return 0;
}
std::string's compare() Method
When dealing with std::string objects, the compare() method is a versatile way to compare strings. It works similarly to strcmp, returning 0 for equal strings, a negative value if the first string is lexicographically smaller, and a positive value if it is larger.
Example:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
if (str1.compare(str2) == 0) {
std::cout << "Strings are equal";
} else {
std::cout << "Strings are not equal";
}
return 0;
}
==)
The equality operator (==) is the simplest way to compare std::string objects in C++. It checks for equality and returns a boolean value.
Example:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "Hello";
if (str1 == str2) {
std::cout << "Strings are equal";
} else {
std::cout << "Strings are not equal";
}
return 0;
}
1. Case-sensitive comparison:
std::string str1 = "hello";
std::string str2 = "Hello";
bool areEqual = (str1 == str2); // false
2. Case-insensitive comparison (using std::transform):
#include <algorithm>
#include <string>
#include <iostream>
int main() {
std::string str1 = "Hello";
std::string str2 = "hello";
std::transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
std::transform(str2.begin(), str2.end(), str2.begin(), ::tolower);
if (str1 == str2) {
std::cout << "Strings are equal (case-insensitive)";
} else {
std::cout << "Strings are not equal";
}
return 0;
}
For more detailed information, you can refer to the official C++ documentation:
Jorge García
Fullstack developer