Bibliothèque de chaînes C ++ - comparer

La description

Il compare la valeur de l'objet chaîne (ou d'une sous-chaîne) à la séquence de caractères spécifiée par ses arguments.

Déclaration

Voici la déclaration pour 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;

Paramètres

  • str - C'est un objet string.

  • len - Il est utilisé pour copier les caractères.

  • pos - Position du premier caractère à copier.

Valeur de retour

Il renvoie une intégrale signée indiquant la relation entre les chaînes.

Exceptions

si une exception est levée, il n'y a aucun changement dans la chaîne.

Exemple

Dans l'exemple ci-dessous pour 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;
}

L'exemple de sortie devrait être comme ceci -

green mango is not red mango
still, green mango is an mango
and red mango is also an mango
therefore, both are mangos