WAP to compare two string
Objective
Write a C++ program to compare two strings for exact equality.
Algorithm / Approach
- Read two strings into
s1ands2. - Use the equality operator:
if (s1 == s2). - If true, print that the strings are equal.
- If false, print that they are unequal.
main.cpp
#include<iostream>
using namespace std;
int main() {
string s1,s2;
cout<<"Enter 1st string : ";
getline(cin,s1);
cout<<"Enter 2nd string : ";
getline(cin,s2);
if(s1==s2) {
cout<<"Strings are equals ";
}
else {
cout<<"Strings are unequals ";
}
return 0;
}
Expected Output
Enter 1st string : cprowess Enter 2nd string : c++prowess strings are unequal
Explanation of the Program
- Once again, the C++
stringclass overloads operators to make your life easier. - The
==operator automatically loops through both strings and compares them character by character. It returns true ONLY if both strings are exactly the same length and contain the exact same characters in the exact same order (case-sensitive).
Complexity
Time Complexity
O(n) - In the worst case where they are equal.
Space Complexity
O(1)