Home »
C++ STL
Compare two string objects in C++ | C++ STL
C++ STL string::compare() function: Here, we are going to learn how to compare two string objects in C++ using C++ STL (Standard Template Library ) functions?
Submitted by Vivek Kothari, on November 11, 2018
String class in C++
String class in C++ is a container used to manage strings and it has many advantages than ordinary c-string. In many programming problems, we require to compare two strings, in this article we discuss library function used to compare two string class objects in C++.
Comparing two string objects in C++
We use std::string::compare() function to comparing two string objects. It returns '0' if both the strings are equal, integer < 0 if the compared string is shorter and an integer > 0 if the compared string is longer. We can use std::string::compare() function in various forms according to need, some methods are discussed below.
References: std::string::compare()
Syntax
string::compare (const string& str) const
Example 1
#include <iostream>
using namespace std;
int main() {
string s1("includehelp");
string s2("include");
string s3("includehelp");
if ((s1.compare(s2)) == 0)
cout << s1 << " is equal to " << s2 << endl;
else
cout << s1 << " didn't match to " << s2 << endl;
if ((s1.compare(s3)) == 0)
cout << s1 << " is equal to " << s3 << endl;
else
cout << s1 << " didn't match to " << s3 << endl;
return 0;
}
Output
includehelp didn't match to include
includehelp is equal to includehelp
Example 2
Here, pos is the index of string from which you want to compare and len denotes the length of the compared string after pos. following code shows the working of this syntax :
#include <iostream>
using namespace std;
int main() {
string s1("help");
string s2("includehelp");
// Compares 4 characters from index 7 of s2 with s1
if ((s2.compare(7, 4, s1)) == 0)
cout << s1 << " is equal to " << s2.substr(7) << endl;
else
cout << s1 << " didn't match to " << s2.substr(7) << endl;
return 0;
}
Output
help is equal to help
Example 3
It compares len characters from index number pos of first string with sublen characters from index subpos of string compared string i.e str. following code shows the working of this syntax :
#include <iostream>
using namespace std;
int main() {
string s1("includenothelp");
string s2("helpinclude");
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "Compares 7 characters from index 0 of s1 with 7 characters from "
"index 4 of s2 "
<< endl;
// Compares 7 characters from index 0 of s1 with 7
// characters from index 4 of s2
if ((s1.compare(0, 7, s2, 4, 7)) == 0)
cout << s1.substr(0, 7) << " of " << s1 << " is equal to " << s2.substr(4)
<< " of " << s2 << endl;
else
cout << " didn't match " << endl;
return 0;
}
Output
Compares 7 characters from index 0 of s1 with 7 characters from index 4 of s2
include of includenothelp is equal to include of helpinclude