Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Return type
3.
Example
3.1.
C++
4.
Different Syntaxes for string::compare():
4.1.
compare(const string& str)
4.1.1.
Example
4.2.
compare(size_t pos, size_t len, const string& str)
4.2.1.
Example
4.3.
compare(const char* s)
4.3.1.
Example
4.4.
compare(size_t pos, size_t len, const char* s)
4.4.1.
Example
5.
Frequently Asked Questions
5.1.
What happens if the strings being compared have different lengths?
5.2.
Is string compare() case-sensitive?
5.3.
Can I use string compare() to compare strings in reverse order?
6.
Conclusion
Last Updated: Jun 14, 2024
Easy

String Compare in C++

Author Riya Singh
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

String comparison is a basic concept in C++ programming. It allows you to compare two strings & determine their relationship. Whether you're checking if two strings are equal, determining which string comes first alphabetically, or searching for a substring within a larger string, the string compare function in C++ makes it easy to perform these operations. 

String Compare in C++

In this article, we'll discuss the different ways to compare strings in C++, including the string compare() function & its various syntaxes.

Return type

The string compare() function in C++ returns an integer value that indicates the relationship between the two strings being compared. The return value can be one of three possibilities:

  1. A negative value: If the first string is considered "less than" the second string, the function returns a negative value. This means that the first string comes before the second string in lexicographical order.
     
  2. Zero: If the two strings are exactly equal, the function returns zero. This indicates that the strings have the same content & length.
     
  3. A positive value: If the first string is considered "greater than" the second string, the function returns a positive value. This means that the first string comes after the second string in lexicographical order.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example

  • C++

C++

#include <iostream>

#include <string>

int main() {

   std::string str1 = "Hello";

   std::string str2 = "World";

   std::string str3 = "Hello";

   int result1 = str1.compare(str2);

   int result2 = str2.compare(str1);

   int result3 = str1.compare(str3);

   std::cout << "Comparing 'Hello' & 'World': " << result1 << std::endl;

   std::cout << "Comparing 'World' & 'Hello': " << result2 << std::endl;

   std::cout << "Comparing 'Hello' & 'Hello': " << result3 << std::endl;

   return 0;

}

Output:

Comparing 'Hello' & 'World': -1
Comparing 'World' & 'Hello': 1
Comparing 'Hello' & 'Hello': 0


In the example above, we compare three pairs of strings using the string compare() function. The first comparison between "Hello" & "World" returns a negative value (-1) because "Hello" comes before "World" in lexicographical order. The second comparison between "World" & "Hello" returns a positive value (1) because "World" comes after "Hello". Finally, the third comparison between "Hello" & "Hello" returns zero because the strings are equal.

Different Syntaxes for string::compare():

The string compare() function in C++ provides several syntaxes to compare strings in different ways. They are:

compare(const string& str)

  • This syntax compares the current string with another string str.
     
  • It returns a negative value if the current string is less than str, zero if they are equal, & a positive value if the current string is greater than str.

Example

std::string str1 = "Hello";
std::string str2 = "World";
int result = str1.compare(str2);

compare(size_t pos, size_t len, const string& str)

  • This syntax compares a substring of the current string with another string str.
     
  • The substring starts at position pos & has a length of len characters.
     
  • It returns a negative value if the substring is less than str, zero if they are equal, & a positive value if the substring is greater than str.


Example

std::string str1 = "Hello, World!";
std::string str2 = "World";
int result = str1.compare(7, 5, str2);

compare(const char* s)

  • This syntax compares the current string with a null-terminated C-style string s.
     
  • It returns a negative value if the current string is less than s, zero if they are equal, & a positive value if the current string is greater than s.

Example

std::string str1 = "Hello";
const char* str2 = "World";
int result = str1.compare(str2);

compare(size_t pos, size_t len, const char* s)

  • This syntax compares a substring of the current string with a null-terminated C-style string s.
     
  • The substring starts at position pos & has a length of len characters.
     
  • It returns a negative value if the substring is less than s, zero if they are equal, & a positive value if the substring is greater than s.

Example

std::string str1 = "Hello, World!";
const char* str2 = "World";
int result = str1.compare(7, 5, str2);

Frequently Asked Questions

What happens if the strings being compared have different lengths?

If the strings have different lengths, the comparison is performed until the end of the shorter string is reached. If all characters up to that point are equal, the longer string is considered greater.

Is string compare() case-sensitive?

Yes, string compare() is case-sensitive by default. It treats uppercase & lowercase characters as distinct. If you want to perform a case-insensitive comparison, you can convert both strings to lowercase or uppercase before comparing them.

Can I use string compare() to compare strings in reverse order?

Yes, you can use the string compare() function with reverse iterators to compare strings in reverse order. Alternatively, you can reverse the strings first & then perform the comparison using the standard syntaxes.

Conclusion

In this article, we have learned about the string compare() function in C++ & its various syntaxes. We explained how to compare entire strings, substrings, & C-style strings using different variations of the compare() function. We also discussed the return values of string compare() & their meanings. With the help of these concepts, you can effectively compare strings in your C++ programs & make decisions based on the comparison results. String comparison is a fundamental operation in programming, & mastering it will help you write more efficient & robust code.

You can refer to our guided paths on Code 360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass