#include <iostream>
#include <string.h>
#include <bits/stdc++.h>
using namespace std;
void compare(string s1, string s2){
if(s1 != s2){
cout<< s1 << " is not equal to "<< s2 <<endl;
if(s1 > s2){
cout << s1 <<" is greater then "<<s2<<endl;
}
else{
cout<< s2 <<" is greater then " << s1 <<endl;
}
}
else
cout<< s1 << " is equal to " << s2 <<endl;
}
int main(){
string s1("ocean");
string s2("labz");
compare(s1,s2);
string s3("OceanLabz");
string s4("OceanLabz");
compare(s3,s4);
return 0;
}
Output:
ocean is not equal to labz
ocean is greater than labz
OceanLabz is equal to OceanLabz
Explanation:
Step1: compare
Function
void compare(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;
}
}
else
cout<< s1 << " is equal to " << s2 <<endl;
}
This function compares two string
objects, s1
and s2
, and provides three possible outcomes:
- If the two strings are not equal, it prints a message saying so, and then compares which one is lexicographically greater.
- If
s1 > s2
, it prints thats1
is greater. - Otherwise, it prints that
s2
is greater. - If the two strings are equal, it prints a message indicating that the strings are equal.
Step2: main()
Function
int main(){
string s1("ocean");
string s2("labz");
compare(s1,s2);
string s3("OceanLabz");
string s4("OceanLabz");
compare(s3,s4);
return 0;
}
In the main()
function:
- First comparison:
s1
is initialized to"ocean"
ands2
to"labz"
. Thecompare(s1, s2)
function is called to compare the two strings.- Since
"ocean"
is lexicographically greater than"labz"
, the output will reflect that.
- Second comparison:
s3
ands4
are both initialized to"OceanLabz"
. Thecompare(s3, s4)
function is called to compare them.- Since
s3
ands4
are equal, the output will show that they are identical.
Step3: Output
For the comparison between s1
("ocean"
) and s2
("labz"
):
"ocean"
is not equal to"labz"
."ocean"
is lexicographically greater than"labz"
because the first differing character is'o'
(ASCII value 111), which is greater than'l'
(ASCII value 108).
For the comparison between s3
("OceanLabz"
) and s4
("OceanLabz"
):
- The strings are equal.