Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to compare two string

C++ Code Example — String Programs

ADVERTISEMENT

WAP to compare two string

Objective

Write a C++ program to compare two strings for exact equality.

Algorithm / Approach

  1. Read two strings into s1 and s2.
  2. Use the equality operator: if (s1 == s2).
  3. If true, print that the strings are equal.
  4. 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++ string class 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)
ADVERTISEMENT