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

The std::string::compare() function in C++ is used to compare two strings lexicographically. It is a member function of the std::string class defined in the <string> header. The function returns an integer value that indicates the relationship between the two strings being compared.

Syntax:

int compare(const string& str) const;
int compare(const char* s) const;
int compare(size_t pos1, size_t count1, const string& str) const;
int compare(size_t pos1, size_t count1, const char* s) const;
int compare(size_t pos1, size_t count1, const string& str, size_t pos2, size_t count2) const;
int compare(size_t pos1, size_t count1, const char* s, size_t count2) const;

Return Value:

  • <0 : If the object string is lexicographically less than the argument string.
  • 0: If the object string is lexicographically equal to the argument string.
  • >0: If the object string is lexicographically greater than the argument string

Examples: 

  1. Basic comparison of two strings:
#include<iostream>
#include<string>
using namespace std;

int main(){
  string str1 = "hello";
  string str2 = "world";
  string str3 = "hello";

  int result1 = str1.compare(str2);
  int result2 = str1.compare(str3);

  cout<<"Comparing hello with world: "<<result1<<endl;
  cout<<"Comparing hello with hello: "<<result2<<endl;

  return 0;
}

Output:

str1.compare(str2) = -1
str1.compare(str3) = 0

2. Compare a substring:

#include<iostream>
#include<string>
using namespace std;

int main(){
  str1 = "Hello, World!";
  str2 = "World";

  int result3 = str1.compare(7, 5, str2);
  int result4 = str1.compare(7, 5, "World!");

  cout<<"str1.compare(7, 5, str2) = "<<result3<<endl;
  cout<<"str1.compare(7, 5, \"World!\") = "<<result4<<endl;

  return 0;
}

Output:

str1.compare(7, 5, str2) = 0
str1.compare(7, 5, "World!") = -1

The compare() function returns the following values:

  • Negative value: If the string object is lexicographically less than the compared string.
  • Zero(0): If the string object is equivalent to the compared string.
  • Positive value: If the string object is lexicographically greater than the compared string.

The comparison is performed based on the character values in the strings, following the lexicographical order defined by the character traits used by the string object.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top