Comparing two string using comparison operators in C++ STL

C++ STL | string comparison: In this article, we are going to see how we can use comparison operators to compare two strings in C++?
Submitted by Radib Kar, on February 27, 2019

String as datatype

In C, we know string basically a character array terminated by \0. Thus to operate with the string we define character array. But in C++, the standard library gives us the facility to use the string as a basic data type like an integer. Like integer comparisons, we can do the same for strings too.

Example:

    Like we define and declare,

    int i=5, j=7;
    Same way, we can do for a string like,

    string s1="Include", s2="Help";

    Like integers (i==j) , (i>j), (i<j)
    We can also do the same like
    if(s1==s2)
        cout << 'They are same\n";
    else if(s1>s2)
        cout<<s1<<" is greater\n";
    else
        cout<<s2<< "s2 is greater\n"; 

Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.

How comparison between two string works?

'==' operator

Two strings need to be lexicographically same to return true which checking for == operator. "Include" and "Include" is the same. But, "INCLUDE" and "Include" is not same, i.e., case matters.

'>' , '<' operator

This two operator checks which string is greater(smaller) lexicographically. The checking starts from the initial character & checking is done as per ascii value. The checking continues until it faces the same character from both strings. Like,

    "Include" > "Help" as 'I' > 'H'
    "Include" < "India" as 'c' < 'd'

Header file needed:

    #include <string>
    Or
    #include <bits/stdc++.h>

C++ program to compare two strings using comparison operator (==)

#include <bits/stdc++.h>
using namespace std;

void compare(string a, string b){
	if(a==b)
		cout<<"strings are equal\n";
	else if(a<b)
		cout<<b<<" is lexicografically greater\n";
	else
		cout<<a<<" is lexicografically greater\n";
}

int main(){
	string s1,s2;
	
	cout<<"enter string1\n";
	cin>>s1;
	cout<<"enter string2\n";
	cin>>s2;
	
	compare(s1,s2); //user-defined function to comapre
	
	return 0;
}

Output

First run:
enter string1
Include
enter string2
Help
Include is lexicografically greater

Second run:
enter string1
Include
enter string2
India
India is lexicografically greater



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.