compare string c++
// CPP code perform relational
// operation using compare function
#include <iostream>
using namespace std;
void compareFunction(string s1, string s2)
{
// comparing both using inbuilt function
int x = s1.compare(s2);
if (x != 0)
cout << s1 << " is not equal to "
<< s2 << endl;
if (x > 0)
cout << s1 << " is greater than "
<< s2 << endl;
else
cout << s2 << " is greater than "
<< s1 << endl;
}
// Main function
int main()
{
string s1("Geeks");
string s2("forGeeks");
compareFunction(s1, s2);
return 0;
}
// comparing apples with apples
#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 apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)
std::cout << "and " << str2 << " is also an apple\n";
if (str1.compare(6,5,str2,4,5) == 0)
std::cout << "therefore, both are apples\n";
return 0;
}
// CPP code to implement relational
// operators on string objects
#include <iostream>
using namespace std;
void relationalOperation(string s1, string s2)
{
if (s1 != s2)
cout << s1 << " is not equal to "
<< s2 << endl;
if (s1 > s2)
cout << s1 << " is greater than "
<< s2 << endl;
else
cout << s2 << " is greater than "
<< s1 << endl;
}
// Main function
int main()
{
string s1("Geeks");
string s2("forGeeks");
relationalOperation(s1, s2);
return 0;
}