The Wayback Machine - https://web.archive.org/web/20241122231704/https://www.geeksforgeeks.org/c-program-to-compare-two-strings-using-operator-overloading/
Open In App

C++ program to compare two Strings using Operator Overloading

Last Updated : 18 May, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pre-requisite: Operator Overloading in C++
Given two strings, how to check if the two strings are equal or not, using Operator Overloading.

Examples: 

Input: ABCD, XYZ
Output: ABCD is not equal to XYZ
        ABCD is greater than XYZ

Input: Geeks, Geeks
Output: Geeks is equal to Geeks

Approach: Using binary operator overloading. 

  • Declare a class with a string variable and operator function ‘==’, ‘<=’ and ‘>=’ that accepts an instance of the class and compares it’s variable with the string variable of the current instance.
  • Create two instances of the class and initialize their class variables with the two input strings respectively.
  • Now, use the overloaded operator(==, <= and >=) function to compare the class variable of the two instances.

Below is the implementation of the above approach: 

C++




// C++ program to compare two Strings
// using Operator Overloading
 
#include <cstring>
#include <iostream>
#include <string.h>
 
using namespace std;
 
// Class to implement operator overloading
// function for concatenating the strings
class CompareString {
 
public:
    // Classes object of string
    char str[25];
 
    // Parameterized Constructor
    CompareString(char str1[])
    {
        // Initialize the string to class object
        strcpy(this->str, str1);
    }
 
    // Overloading '==' under a function
    // which returns integer 1/true
    // if left operand string
    // and right operand string are equal.
    //(else return 0/false)
    int operator==(CompareString s2)
    {
        if (strcmp(str, s2.str) == 0)
            return 1;
        else
            return 0;
    }
 
    // Overloading '<=' under a function
    // which returns integer 1/true
    // if left operand string is smaller than
    // or equal to the right operand string.
    // (else return 0/false)
    int operator<=(CompareString s3)
    {
        if (strlen(str) <= strlen(s3.str))
            return 1;
        else
            return 0;
    }
 
    // Overloading '>=' under a function
    // which returns integer 1/true
    // if left operand string is larger than
    // or equal to the right operand string.
    //(else return 0/false)
    int operator>=(CompareString s3)
    {
        if (strlen(str) >= strlen(s3.str))
            return 1;
        else
            return 0;
    }
};
 
void compare(CompareString s1, CompareString s2)
{
 
    if (s1 == s2)
        cout << s1.str << " is equal to "
             << s2.str << endl;
    else {
        cout << s1.str << " is not equal to "
             << s2.str << endl;
        if (s1 >= s2)
            cout << s1.str << " is greater than "
                 << s2.str << endl;
        else
            cout << s2.str << " is greater than "
                 << s1.str << endl;
    }
}
 
// Testcase1
void testcase1()
{
    // Declaring two strings
    char str1[] = "Geeks";
    char str2[] = "ForGeeks";
 
    // Declaring and initializing the class
    // with above two strings
    CompareString s1(str1);
    CompareString s2(str2);
 
    cout << "Comparing \"" << s1.str << "\" and \""
         << s2.str << "\"" << endl;
 
    compare(s1, s2);
}
 
// Testcase2
void testcase2()
{
    // Declaring two strings
    char str1[] = "Geeks";
    char str2[] = "Geeks";
 
    // Declaring and initializing the class
    // with above two strings
    CompareString s1(str1);
    CompareString s2(str2);
 
    cout << "\n\nComparing \"" << s1.str << "\" and \""
         << s2.str << "\"" << endl;
 
    compare(s1, s2);
}
 
// Driver code
int main()
{
    testcase1();
    testcase2();
 
    return 0;
}


Output: 

Comparing "Geeks" and "ForGeeks"
Geeks is not equal to ForGeeks
ForGeeks is greater than Geeks


Comparing "Geeks" and "Geeks"
Geeks is equal to Geeks

 



Previous Article
Next Article

Similar Reads

Operator Overloading '<<' and '>>' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Compare two integers without using any Comparison operator
Given two integers A & B. Task is to check if A and B are same or not without using comparison operators.Examples: Input : A = 5 , B = 6Output : 0 Input : A = 5 , B = 5 Output : 1 Note : 1 = "YES" and 0 = "NO" The idea is pretty simple we do Xor of both elements ( A, B ). if Xor is zero then two numbers are equal else not. Below is the implemen
5 min read
Matrix operations using operator overloading
Pre-requisite: Operator OverloadingGiven two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.Examples: Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}} Output: Addition of two given Matrices is: 2 4 6 8 10 22 2 4 6 Subtraction of
13 min read
C++ | Operator Overloading | Question 10
How can we restrict dynamic allocation of objects of a class using new? (A) By overloading new operator (B) By making an empty private new operator. (C) By making an empty private new and new[] operators (D) By overloading new operator and new[] operators Answer: (C) Explanation: If we declare new and [] new operators, then the objects cannot be cr
1 min read
C++ | Operator Overloading | Question 2
Which of the following operators cannot be overloaded (A) . (Member Access or Dot operator) (B) ?: (Ternary or Conditional Operator ) (C) :: (Scope Resolution Operator) (D) .* (Pointer-to-member Operator ) (E) All of the above Answer: (E) Explanation: See What are the operators that cannot be overloaded in C++?Quiz of this Question
1 min read
C++ | Operator Overloading | Question 3
Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written? 1) Comparison Operator ( == ) 2) Assignment Operator ( = ) (A) Both 1 and 2 (B) Only 1 (C) Only 2 (D) None of the two Answer: (C) Explanation: Assign operator is by default available in all user defined classes even
1 min read
C++ | Operator Overloading | Question 4
Which of the following operators should be preferred to overload as a global function rather than a member method? (A) Postfix ++ (B) Comparison Operator (C) Insertion Operator << (D) Prefix++ Answer: (C) Explanation: cout is an object of ostream class which is a compiler defined class. When we do "cout << obj" where obj is an obje
1 min read
C++ | Operator Overloading | Question 5
How does C++ compiler differs between overloaded postfix and prefix operators? (A) C++ doesn't allow both operators to be overloaded in a class (B) A postfix ++ has a dummy parameter (C) A prefix ++ has a dummy parameter (D) By making prefix ++ as a global function and postfix as a member function. Answer: (B) Explanation: See the following example
1 min read
C++ | Operator Overloading | Question 6
Predict the output #include<iostream> using namespace std; class A { int i; public: A(int ii = 0) : i(ii) {} void show() { cout << i << endl; } }; class B { int x; public: B(int xx) : x(xx) {} operator A() const { return A(x); } }; void g(A a) { a.show(); } int main() { B b(10); g(b); g(20); return 0; } (A) Compiler Error (B) 10 2
1 min read
C++ | Operator Overloading | Question 7
Output of following program? #include <iostream> using namespace std; class Test2 { int y; }; class Test { int x; Test2 t2; public: operator Test2 () { return t2; } operator int () { return x; } }; void fun ( int x) { cout << "fun(int) called"; } void fun ( Test2 t ) { cout << "fun(Test 2) called"; } int main()
1 min read
C++ | Operator Overloading | Question 10
Predict the output? #include<stdlib.h> #include<stdio.h> #include<iostream> using namespace std; class Test { int x; public: void* operator new(size_t size); void operator delete(void*); Test(int i) { x = i; cout << "Constructor called \n"; } ~Test() { cout << "Destructor called \n"; } }; void* Test
2 min read
C++ | Operator Overloading | Question 9
#include<iostream> using namespace std; class Point { private: int x, y; public: Point() : x(0), y(0) { } Point& operator()(int dx, int dy); void show() {cout << "x = " << x << ", y = " << y; } }; Point& Point::operator()(int dx, int dy) { x = dx; y = dy; return *this; } int main() { Point p
1 min read
C++ | Operator Overloading | Question 10
Which of the following operator functions cannot be global, i.e., must be a member function. (A) new (B) delete (C) Conversion Operator (D) All of the above Answer: (C) Explanation: new and delete can be global, see following example. #include #include #include using namespace std; class Myclass { int x; public: friend void* operator new(size_t siz
1 min read
Increment (++) and Decrement (--) Operator Overloading in C++
Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types. Why Operator Overloading? Let's say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the re
4 min read
C++ Logical (&&, ||, !) Operator Overloading
Prerequisites: OperatorsOperator Overloading Logical operators are used for combining two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false. In C++, there are 3 logical operators: Logical AND (&&): This operator returns true o
3 min read
C++ Bitwise Operator Overloading
Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ takes two numbers as operands and does AND on every bi
7 min read
Typecast Operator Overloading in C++
In C++, the typecast operator can be overloaded to customize the behavior of casting operators to define how user-defined data types can be converted into other types. This enables developers to define how instances of a class are converted to other types, providing more control over implicit type conversions. By overloading typecast operators, dev
6 min read
Overloading New and Delete operator in c++
The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.If overloading is done out
5 min read
Operator overloading in C++ to print contents of vector, map, pair, ..
Operator overloading is one of the features of Object oriented programming which gives an extra ability to an operator to act on a User-defined operand(Objects). We can take advantage of that feature while debugging the code specially in competitive programming. All we need to do is to overload the stream insertion operator(See this article to unde
3 min read
Rules for operator overloading
In C++, following are the general rules for the things that are not allowed with operator overloading. 1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed. 4) Overloaded operators cannot have default arguments
3 min read
Different Ways of Operator Overloading in C++
In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading. In this article, we will learn the different ways in which we can define the operator function for operator ove
6 min read
Overloading Subscript or array index operator [] in C++
The Subscript or Array Index Operator is denoted by '[]'. This operator is generally used with arrays to retrieve and manipulate the array elements. This is a binary or n-ary operator and is represented in two parts: Postfix/Primary ExpressionExpressionThe postfix expression, also known as the primary expression, is a pointer value such as array or
6 min read
Error: std::endl is of Unknown Type when Overloading Operator <<
In C++, the << operator is commonly overloaded for custom output for user-defined types using streams. However, an issue may arise when using std::endl with an overloaded operator<<. It is shown as the type of std::endl being unknown, leading to compilation errors. In this article, we will learn the cause of this issue and how can we re
4 min read
C++ Assignment Operator Overloading
Prerequisite: Operator Overloading The assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types. Assignment operator overloading is binary operator overloading.Overloading assignment operator in C++ copies all values of one
4 min read
Types of Operator Overloading in C++
C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change some specific operators' functions to do different tasks. Syntax: Return_Type classname :: operator op(Argument list){ Function Body} // This
4 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
9 min read
Compare two strings represented as linked lists
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater. Examples: Input: list1 = g->e-
7 min read
Compare two strings considering only alphanumeric characters
Given two strings that can contain lower and uppercase alphabets, numbers and special characters like dots, blank spaces, commas, etc. Compare both strings considering only alphanumeric characters([a-b], [A-B] and [0-9]) if they are equal or not. For example, strings "Ram, Shyam" and "Ram-Shyam" both are the same and also "/.';[]" and "@# >" are
10 min read
Compare two Linked List of Strings
Given two linked lists L1 and L2 in which in every node a string is stored. The task is to check whether the strings combining all the nodes are similar or not. Examples: Input: L1 = ["He", "llo", "wor", "ld"], L2 = ["H", "e", "ll", "owo", "r", "ld"]Output: trueExplanation: both lists makes the string of "Helloworld". Input: L1 = ["w", "o", "l", "d
11 min read
Compare two strings lexicographically in Java
In this article, we will discuss how we can compare two strings lexicographically in Java. One solution is to use Java compareTo() method. The method compareTo() is used for comparing two strings lexicographically in Java. Each character of both the strings is converted into a Unicode value for comparison. int compareTo(String str) :It returns the
3 min read
three90RightbarBannerImg