Home c++ How to compare two std :: string

How to compare two std :: string

Author

Date

Category

There are two variables of type string .
Suggest methods for comparing them.


Answer 1, authority 100%

Hmm … Just take and compare:

std :: string a = "Hello", b = "World";
...
a & lt; b;
a & gt; b;
a == b;
a! = b;

Answer 2, authority 38%

The strcmp function has a prototype:

int strcmp (const char * str1, const char * str2);

After comparing str1 and str2, this function will return an integer value:

& lt; 0 if str1 & lt; str2
= 0 if str1 = str2
& gt; 0 if str1 & gt; str2

This function performs comparison by distinguishing between uppercase and lowercase

Example:

char s1 [] = "Hello";
char s2 [] = "HeLlo";
int k = strcmp (s1, s2);
cout & lt; & lt; k;

As a result, the screen will display: 32. character code l = 108 and character code L = 76.108-76 = 32.

Taken from here


Answer 3

# include & lt; cstdlib & gt;
#include & lt; iostream & gt;
#include & lt; vector & gt;
using namespace std;
int main () {
  bool check;
  cout & lt; & lt; "Type a text:";
  string text;
  getline (cin, text);
  cout & lt; & lt; "Type else text:";
  string text2;
  getline (cin, text2);
  vector & lt; char & gt; res2 (text2.begin (), text2.end ());
  vector & lt; char & gt; res (text.begin (), text.end ());
  for (auto i = res.begin (); i & lt; res.end (); ++ i) {
    while (isupper (* i)) {
* i = tolower (* i);
      }
    for (auto j = res2.begin (); j & lt; res2.end (); ++ j) {
      while (isupper (* j)) {
        * j = tolower (* j);
      }
      if (* i == * j) {
        check = true;
      } else {
        check = false;
      }
    }
  }
  if (check == false) {
    cout & lt; & lt; "first string differ from second one \ n";
  } else {
    cout & lt; & lt; "First string is the same as second \ n";
  }
  cout & lt; & lt; check;
return 0;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions