Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
std::basic_string::at in C++
Next article icon

std::string::compare() in C++

Last Updated : 06 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 compare string using string::compare() function are as follows:

Table of Content

  • Compare Two Strings
  • Compare Substring with Another String
  • Compare Substring with Another Substring

Compare Two Strings

The string::compare() method can be used to compare the one string with another string that is passed to it as argument.

Syntax

str1.compare(str2);

Parameters

  • str1: First string with another string is to be compared.
  • str2: Another string.

Return Value

  • Returns 0 if str1 is equal to str2.
  • Returns a positive integer when the first not-matching character in str1 has a greater ASCII value than the corresponding character in str2.
  • Returns a negative integer when the first not-matching character in str1 has a lesser ASCII value than the corresponding character in str2.

Example

C++
// C++ program to show how to use string::compare() // to compare the two strings #include <bits/stdc++.h> using namespace std;  int main() {     string str1("Geeks");     string str2("Geeks");      // Comparing str1 and str2     if ((str1.compare(str2)) == 0)         cout << "String Matched" << endl;     else         cout << "String Not Matched" << endl;      return 0; } 

Output
String Matched 

Time Complexity: O(n), where n is the length of the smaller string.
Auxiliary space: O(1)

Compare Substring with Another String

The string::compare() method also supports the comparison between a part of the string with another string.

Syntax

str1.compare(pos, n, str2);

Parameters

  • str1: First string with another string is to be compared.
  • str2: Another string.
  • pos: Starting index of substring taken from str1.
  • n: Number of characters to compare.

Return Value

  • Returns 0 if substring is equal to str2.
  • Returns a positive integer when the first not-matching character in substring has a greater ASCII value than the corresponding character in str2.
  • Returns a negative integer when the first not-matching character in substring has a lesser ASCII value than the corresponding character in str2.

Example

C++
// C++ program to show how to use string::compare() // to compare string with a part of another string #include <bits/stdc++.h> using namespace std;  int main() {     string str1("forGeeks");     string str2("Geeks");      // Compares 5 characters starting from index     // 3 of str1 with str2     if ((str1.compare(3, 5, str2)) == 0)         cout << "Substring Matched";     else         cout << "Strings Not Matched";      return 0; } 

Output
Substring Matched

Time Complexity: O(n), where n is the length of the substring.
Auxiliary space: O(1)

Explanation: Here we compare substring made by the 5 characters of str1 starting from index 3 i.e. “Geeks” with string str2 i.e. “Geeks”. As they are equal, ‘String Matched’ is printed.

Compare Substring with Another Substring

We can also compare the part of first string with the part of another string using the string::compare() method. In this case, we will need to define both the substring as shown below:

Syntax

str1.compare(pos1, n1, str2, pos2, n2);

Parameters

  • str1: First string with another string is to be compared.
  • pos1: Starting index of substring taken from str1.
  • n1: Number of characters to compare from str1.
  • str2: Another string.
  • pos2: Starting index of substring taken from str2.
  • n2: Number of characters to compare from str2.

Return Value

  • Returns 0 if str1’s substring is equal to str2’s substring.
  • Returns a positive integer Returns a positive integer when the first not-matching character in str1’s substring has a greater ASCII value than the corresponding character in str2’s substring.
  • Returns a negative integer when the first not-matching character in str1’s substring has a lesser ASCII value than the corresponding character in str2. is greater than str2’s substring.

Example

C++
// C++ Program to show how to use string::compare() // to compare the one substring with another substring #include <bits/stdc++.h> using namespace std;  int main() {     string str1("Geeks");     string str2("forGeeks");      // Compares 5 characters of str1 starting from     // index 0 with 5 characters of str2 starting     // from index 3     if ((str1.compare(0, 5, str2, 3, 5)) == 0)         cout << "Both Substring Matches";      else         cout << "Substrings Not Matched";      return 0; } 

Output
Both Substring Matches

Time Complexity: O(n), where n is the length of the smaller substring.
Auxiliary space: O(1)

Explanation: Here we compare the first 5 character of str1 “Geeks” with 5 character from str2 “Geeks” starting with index 3.



Next Article
std::basic_string::at in C++

S

Sakshi Tiwari
Improve
Article Tags :
  • C++
  • CPP-Functions
  • cpp-string
  • cpp-strings-library
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • std::string::clear in C++
    The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters. Parameters: none Return Value: none void string ::clear () - Removes all characters (makes string empty) - Doesn't throw any error - Receives no parameters and returns nothing // CPP
    1 min read
  • std::string class in C++
    C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. String vs Character ArrayString Ch
    8 min read
  • std::string::data() in C++
    The data() function writes the characters of the string into an array. It returns a pointer to the array, obtained from conversion of string to the array. Its Return type is not a valid C-string as no '\0' character gets appended at the end of array. Syntax: const char* data() const; char* is the po
    2 min read
  • std::basic_string::at in C++
    Returns a reference to the character at the specified location pos. The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not. Syntax: reference at (size_type po
    1 min read
  • std::string::assign() in C++
    The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this C/C++ Code // CPP code for
    5 min read
  • std::string::push_back() in C++
    The std::string::push_back() method in C++ is used to append a single character at the end of string. It is the member function of std::string class defined inside <string> header file. In this article, we will learn about std::string::push_back() method in C++. Example: [GFGTABS] C++ // C++ P
    2 min read
  • std::string::append() in C++
    The string::append() in C++ is used append the characters or the string at the end of the string. It is the member function of std::string class . The string::append() function can be used to do the following append operations: Table of Content Append a Whole StringAppend a Part of the StringAppend
    3 min read
  • std::string::size() in C++
    The std::string::size() function in C++ is a built-in method of the std::string class that is used to determine the number of characters in the string. All characters up to the null character are considered while calculating the size of the string. In this article, we will learn about string::size()
    2 min read
  • std::string::back() in C++ with Examples
    This function returns a direct reference to the last character of the string. This shall only be used on non-empty strings. This can be used to access the last character of the string as well as to append a character at the end of the string. Length of the string remains unchanged after appending a
    2 min read
  • char* vs std:string vs char[] in C++
    In this article, we are going to inspect three different ways of initializing strings in C++ and discuss differences between them. 1. Using char* Here, str is basically a pointer to the (const)string literal. Syntax: char* str = "This is GeeksForGeeks";Pros: 1. Only one pointer is required to refer
    6 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