Several string comparison operators are defined in the string class and these operators operate by comparing the string characters and all these comparisons are case-sensitive. But one extra point to keep in mind is that when we do a comparison of two strings using a relational operator then comparison takes place lexicographically.
What is lexicographical order?
Lexicographical order is basically a dictionary order of arranging words. For example, In a dictionary, the word 'Accutane' will come before 'Accutron' because the letter 'a' comes before 'r' in the English alphabetic system.
List of Relational Operators:
- Equal to (==): This operator is used to test the equality of two strings.
- Not Equal to (!=): This operator is used to test whether two strings are unequal.
Note: Two strings are said to be equal when they have the same length and contain the same characters.
C++ example code:
/*C++ program to check equality operator*/ #include<iostream> #include<string> using namespace std; int main(){ string str1 = "Welcome to Algolesson"; string str2 = "welcome to algolesson"; if(str1 == str2) cout<<"Both the string are equal"<<endl; if(str1 != str2) cout<<"Both the strings are not equal"<<endl; return 0; }
Both the strings are not equal
- Greater than(>): This operator is used to check whether one string is greater than another string.
- Lesser than (<): This operator is used to check whether one string is lesser than another string.
- Greater than and equal to (>=): This operator is used to check whether one string is greater than or equal to another string.
- Lesser than and equal to (>=): This operator is used to check whether one string is lesser than or equal to another string.
/*C++ program to check relational operator*/ #include<iostream> #include<string> using namespace std; int main(){ string str1 = "Accutane"; string str2 = "Accutron"; string str3 = "Axe"; if((str1 > str2) && (str1 > str3)) cout<<"Largest string is: "<<str1<<endl; else if((str2 > str1) && (str2 > str3)) cout<<"Largest string is: "<<str2<<endl; else cout<<"Largest string is: "<<str3<<endl; return 0; }
Largest string is: Axe
I hope you are now able to understand how string comparison takes place in lexicographical order when we use relational operators.
Next:
(getButton) #text=(String Member Functions in C++) #icon=(link) #color=(#2339bd)
No comments:
Post a Comment