C++ String Library - compare



Description

It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments.

Declaration

Following is the declaration for std::string::compare.

int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;

C++11

int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;

C++14

int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen = npos) const;

Parameters

  • str − It is a string object.

  • len − It is used to copy the characters.

  • pos − Position of the first character to be copied.

Return Value

It returns a signed integral indicating the relation between the strings.

Exceptions

if an exception is thrown, there are no changes in the string.

Example

In below example for std::string::compare.

#include <iostream>
#include <string>

int main () {
   std::string str1 ("green mango");
   std::string str2 ("red mango");

   if (str1.compare(str2) != 0)
      std::cout << str1 << " is not " << str2 << '\n';

   if (str1.compare(6,5,"mango") == 0)
      std::cout << "still, " << str1 << " is an mango\n";

   if (str2.compare(str2.size()-5,5,"mango") == 0)
      std::cout << "and " << str2 << " is also an mango\n";

   if (str1.compare(6,5,str2,4,5) == 0)
      std::cout << "therefore, both are mangos\n";

   return 0;
}

The sample output should be like this −

green mango is not red mango
still, green mango is an mango
and red mango is also an mango
therefore, both are mangos
string.htm
Advertisements