Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Compare two string

#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 that s1 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:

  1. First comparison:
    • s1 is initialized to "ocean" and s2 to "labz". The compare(s1, s2) function is called to compare the two strings.
    • Since "ocean" is lexicographically greater than "labz", the output will reflect that.
  2. Second comparison:
    • s3 and s4 are both initialized to "OceanLabz". The compare(s3, s4) function is called to compare them.
    • Since s3 and s4 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.

    Leave a Reply

    Your email address will not be published.

    Need Help?