To compare two strings in C++
In this tutorial, we will learn how to compare two strings in C++. We will check whether they are equal or not. For example-
str1=”codespeedy”
str2=”codespeedy”
They are equal.
str1=”hello peter”
str2=”hello paul”
They are not equal.
Here we are going to show you two different methods.
- using relational operator
- using strcmp function
For the lazy programmers, it is better to use strcmp. ( Not always seems to be easy )
How to compare two strings in C++
There are two approaches:
By using the relational operator:
Here we will use the relational operator in between two strings to compare with each other.
#include <iostream>
using namespace std;
void compare(string s1, string s2)
{
if (s1 != s2)
cout << "Not equal";
else
cout << "Equal";
}
int main()
{
char s1[]="codespeedy";
char s2[]="codespeedy";
compare(s1, s2);
return 0;
}
Output:
Equal
By using strcmp function:
This below program is much easier as we have used a built-in function to achieve our goal.
#include<bits/stdc++.h>
using namespace std;
int main()
{
char str1[]="hello peter";
char str2[]="hello paul";
if(strcmp(str1,str2)==0)
{
cout<<"Equal";
}
else
{
cout<<"Not equal";
}
}
If the value of strcmp is greater then 0, it means that string1 is greater than string2.
Output:
Not equal
Also, refer to:
Count the number of occurrences of an element in a linked list in C++
Leave a Reply