In C++, string manipulation is a common task, and comparing strings is a fundamental operation. The std::string::compare
function in C++ provides a powerful and flexible way to compare strings and substrings. This article delves into the intricacies of Cpp Compare
, exploring its syntax, parameters, return values, and use cases with clear examples, making it an essential guide for C++ developers.
Understanding std::string::compare
The std::string::compare
function is a member function of the std::string
class in C++. It allows you to compare a string object (or a portion of it) with another string, a C-string, or a character buffer. This function is crucial for tasks like sorting strings, searching for specific strings, and implementing conditional logic based on string comparisons.
Unlike simple equality operators (==
, !=
), compare
provides more detailed information about the relationship between two strings. It not only tells you if strings are equal but also indicates their lexicographical order if they are not.
Syntax and Parameters of cpp compare
The std::string::compare
function offers several overloaded versions to handle different comparison scenarios. Here’s a breakdown of the common syntaxes:
1. Comparing with another std::string
object:
int compare (const string& str) const noexcept;
str
: The string object to compare with.
2. Comparing substrings with another std::string
object:
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
pos
: The starting position of the substring within the string object calling thecompare
function.len
: The length of the substring to compare.str
: The string object to compare with.subpos
: The starting position of the substring within thestr
object.sublen
: The length of the substring within thestr
object.
3. Comparing with a C-string:
int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
s
: A pointer to a null-terminated C-string.
4. Comparing with a character buffer:
int compare (size_t pos, size_t len, const char* s, size_t n) const;
s
: A pointer to a character array (buffer).n
: The number of characters to use from the character buffer.
Parameters Explained:
pos
andlen
: These parameters allow you to specify a substring of the string object on whichcompare
is called.pos
is the starting index (0-based), andlen
is the number of characters to include in the substring. Ifpos
is out of range, it throwsstd::out_of_range
exception.str
ands
: These are the strings or character sequences that are being compared against the string object.subpos
andsublen
: Similar topos
andlen
, but they define a substring within thestr
object being used for comparison in the second substring version.n
: When comparing with a character buffer (char* s
),n
specifies how many characters from the buffer should be considered for comparison.
Return Values Explained
The std::string::compare
function returns an integer value that indicates the relationship between the “compared string” (the string object or substring) and the “comparing string” (the argument passed to the function).
Return Value | Relationship between Compared String and Comparing String |
---|---|
0 |
The strings are equal. |
< 0 |
The compared string is lexicographically less than the comparing string. This can happen in two scenarios: 1. The first differing character in the compared string has a lower value. 2. All compared characters are equal, but the compared string is shorter. |
> 0 |
The compared string is lexicographically greater than the comparing string. This can happen in two scenarios: 1. The first differing character in the compared string has a higher value. 2. All compared characters are equal, but the compared string is longer. |
Lexicographical comparison is essentially dictionary order. Strings are compared character by character based on their ASCII values.
Code Examples of cpp compare
in Action
Let’s illustrate cpp compare
with practical examples:
#include <iostream>
#include <string>
int main() {
std::string str1 = "green apple";
std::string str2 = "red apple";
if (str1.compare(str2) != 0) {
std::cout << """ << str1 << "" is not equal to "" << str2 << """ << std::endl;
}
if (str1.compare(6, 5, "apple") == 0) {
std::cout << "The substring "apple" is found in "" << str1 << "" starting from position 6" << std::endl;
}
if (str2.compare(str2.size() - 5, 5, "apple") == 0) {
std::cout << "The substring "apple" is also found at the end of "" << str2 << """ << std::endl;
}
if (str1.compare(6, 5, str2, 4, 5) == 0) {
std::cout << "The substring "apple" is the same in both strings" << std::endl;
}
std::string str3 = "banana";
std::string str4 = "blueberry";
if (str3.compare(str4) < 0) {
std::cout << """ << str3 << "" comes before "" << str4 << "" alphabetically" << std::endl;
} else {
std::cout << """ << str4 << "" comes before or is the same as "" << str3 << "" alphabetically" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str1 ("green apple");
std::string str2 ("red apple");
if (str1.compare(str2) != 0)
std::cout << str1 << " is not " << str2 << 'n';
if (str1.compare(6,5,"apple") == 0)
std::cout << "still, " << str1 << " is an applen";
if (str2.compare(str2.size()-5,5,"apple") == 0)
std::cout << "and " << str2 << " is also an applen";
if (str1.compare(6,5,str2,4,5) == 0)
std::cout << "therefore, both are applesn";
return 0;
}
Output of the Example:
"green apple" is not equal to "red apple"
The substring "apple" is found in "green apple" starting from position 6
The substring "apple" is also found at the end of "red apple"
The substring "apple" is the same in both strings
"banana" comes before "blueberry" alphabetically
still, green apple is an apple
and red apple is also an apple
therefore, both are apples
This example demonstrates various uses of cpp compare
, including:
- Comparing entire strings.
- Comparing substrings of a string with a C-string literal.
- Comparing substrings with substrings of another string.
- Lexicographical comparison to determine alphabetical order.
Complexity and Performance
The time complexity of std::string::compare
is generally linear, meaning it takes time proportional to the length of the strings being compared. In most cases, it compares characters sequentially until a difference is found or the end of one of the strings is reached. This makes it efficient for most string comparison tasks.
Exception Safety
std::string::compare
provides strong exception safety. In most overloads, if an exception is thrown, there are no changes to the string object. However, it’s important to note that if you are using C-style strings (char* s
), ensure that the pointer s
is valid and points to a memory location of sufficient size. Otherwise, it can lead to undefined behavior. Specifically, if pos
or subpos
is out of range, std::out_of_range
exception is thrown.
Related Functions
For further string manipulation and comparison in C++, consider exploring these related functions:
std::string::find
: To locate substrings within a string.std::string::replace
: To replace portions of a string.std::string::substr
: To extract substrings from a string.- Relational operators (
==
,!=
,<
,>
,<=
,>=
): For simpler equality and inequality checks.
Conclusion
std::string::compare
is a versatile and essential function for string comparison in C++. Its ability to compare entire strings, substrings, and different string types, along with its detailed return values, makes it a powerful tool for various programming tasks. Understanding and effectively using cpp compare
is crucial for any C++ developer working with string manipulation and data processing.