C++ String compare
This function evaluates the string object's value against the specified sequence of characters provided as its parameter.
Syntax :
If we have two strings, str1 and str2, and we wish to compare them, the syntax for doing so would be:
int k= str1.compare(str2);
- k==0 : If k contains value zero, it means both the strings are equal.
- k!=0 : If k does contain value zero, it means both the strings are unequal.
- k>0 : If k contains value more than zero, either the value of the first character is greater in the compared string or all the compared characters match but the compared string is longer.
- k<0 : If k contains value less than zero, either the value of the first character is lower in the compared string or all the compared characters match but the compared string is shorter.
Example 1
#include<iostream>
using namespace std;
void main()
{
string str1="Hello";
string str2="javacpptutorial";
int k= str1.compare(str2);
if(k==0)
cout<<"Both the strings are equal";
else
cout<<"Both the strings are unequal";
}
Output:
Both the strings are unequal
When comparing the strings str1 and str2, with 'Hello' and 'javacpptutorial' as their respective values, the comparison method yields a negative integer value. Consequently, the 'if' condition does not validate, leading to the execution of the else statement which outputs "Both the strings are unequal".
Example 2
#include<iostream>
using namespace std;
void main()
{
string str1="Welcome to javacpptutorial";
string str2="Welcome to javacpptutorial";
int i=str1.compare(str2);
if(i==0)
cout<<"strings are equal";
else
cout<<"strings are not equal";
}
Output:
Strings are equal