Hi, I wanted to know if is there any simple code that can compare two different strings in C++ easily.
How Do I Compare Two Strings in C++?
Collapse
X
-
Tags: None
-
- Relational operatorsHow Do I Compare Two Strings in C++?
- std::compare()
- strcmp() {C library function}
- Write custom code.
Define 'simple code'.Hi, I wanted to know if is there any simple code that can compare two different strings in C++ easily. -
Here, the comparison can be done in three ways.
one - by using strcmp() function
Two - by using compare() function
or else we can directly compare two strings by using comparison operator.
Here I am showing you one of the way by using comparison operators:
let's say we have 2 strings
string a=”abcd”;
string b=”abcd”;
So here we can simply use ‘==’ operator to check if they are equal or not
if(a==b) return true;
else return false;
In order to know more about this you can read this article here.Comment
-
-
You can use strcmp function to compare two strings.
I've written a code to compare two strings that they are equal or not.
#include <iostream>
using namespace std;
int main ()
{
// declare string variables
string str1;
string str2;
cout << " Enter the String 1: " << endl;
cin >> str1;
cout << " Enter the String 2: " << endl;
cin >> str2;
// use '==' equal to operator to check the equality of the string
if ( str1 == str2)
{
cout << " String is equal." << endl;
}
else
{
cout << " String is not equal." << endl;
}
return 0;
}Comment
Comment