Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Comparing two strings in C++
Next article icon

Comparing two strings in C++

Last Updated : 23 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two strings, how to check if the two strings are equal or not. 
Examples: 

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

This problem can be solved using any of the following two methods  

  • C++ Relational operators
CPP
// CPP code to implement relational // operators on string objects #include <iostream> using namespace std;  void relationalOperation(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; }  // Driver code int main() {     string s1("Geeks");     string s2("forGeeks");     relationalOperation(s1, s2);     string s3("Geeks");     string s4("Geeks");     relationalOperation(s3, s4);     return 0; } 

Output
Geeks is not equal to forGeeks forGeeks is greater than Geeks Geeks is equal to Geeks

Time Complexity: O(min(n,m)) where n and m are the length of the strings.

Auxiliary Space:  O(max(n,m)) where n and m are the length of the strings.

This is because when string is passed in the function it creates a copy of itself in stack.

  • std:: Compare()
CPP
// CPP code perform relational // operation using compare function #include <iostream>  using namespace std;  void compareFunction(string s1, string s2) {     // comparing both using inbuilt function     int x = s1.compare(s2);      if (x != 0) {         cout << s1               << " is not equal to "               << s2 << endl;         if (x > 0)             cout << s1                   << " is greater than "                   << s2 << endl;         else             cout << s2                   << " is greater than "                   << s1 << endl;     }     else         cout << s1 << " is equal to " << s2 << endl; }  // Driver Code int main() {     string s1("Geeks");     string s2("forGeeks");     compareFunction(s1, s2);     string s3("Geeks");     string s4("Geeks");     compareFunction(s3, s4);     return 0; } 

Output
Geeks is not equal to forGeeks forGeeks is greater than Geeks Geeks is equal to Geeks

Time Complexity: O(min(n,m)) where n and m are the length of the strings.

Auxiliary Space:  O(max(n,m)) where n and m are the length of the strings.

This is because when string is passed in the function it creates a copy of itself in stack.

Differences between C++ Relational operators and compare() :-  

  1. compare() returns an int, while relational operators return boolean value i.e. either true or false.
  2. A single Relational operator is unique to a certain operation, while compare() can perform lots of different operations alone, based on the type of arguments passed.
  3. We can compare any substring at any position in a given string using compare(), which otherwise requires the long procedure of word-by-word extraction of string for comparison using relational operators.

Example:- 

  • Using compare()
// Compare 3 characters from 3rd position // (or index 2) of str1 with 3 characters  // from 4th position of str2.  if (str1.compare(2, 3, str2, 3, 3) == 0)    cout<<"Equal"; else    cout<<"Not equal";
  • Using Relational operator
for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++)     {      if (s1[i] != s2[j])        break; } if (i == 6 && j == 7)     cout << "Equal"; else     cout << "Not equal";

The above example clearly shows how compare() reduces lots of extra processing, therefore it is advisable to use it while performing substring comparison at some position, otherwise both perform almost in the same manner.


Next Article
Comparing two strings in C++

S

Sakshi_Tiwari
Improve
Article Tags :
  • Misc
  • Strings
  • DSA
  • cpp-string
Practice Tags :
  • Misc
  • Strings

Similar Reads

    Compare two Strings in Java
    String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
    4 min read
    std::string::compare() in C++
    The string::compare() function in C++ is used to compare a string or the part of string with another string or substring. It is the member function of std::string class defined inside <string> header file. In this article, we will learn how to use string::compare() in C++.The different ways to
    4 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 lexicograph
    7 min read
    C# String CompareOrdinal() Method
    In C#, CompareOrdinal() is a method of the String class. This method is used to compare the two specified string objects or substrings using the numerical values (Unicode) of the corresponding Char objects in each string or substring. It performs a case-sensitive and culture-insensitive comparison.O
    4 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 comp
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences