MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Compare Two Strings with Explanation

C++ Easy Strings 39 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around same, two, compare. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Check if two strings are exactly same or not.
Real Life: Like password verification.

Input Format

Two strings str1 and str2.

Output Format

Print

• Same
OR

• Not Same

Constraints

• Strings length ≥ 1

• Case-sensitive (A ≠ a)

• Compare character by character

Concept Explanation

Two strings are exactly same if:

• They have the same length

• All characters at the same positions are equal

This is used in password verification.

Step-by-Step Logic

1.Take input strings str1 and str2.

2.If lengths are different:

• Print Not Same.

3.Traverse both strings from start to end.

4.Compare characters at each position.

5.If any character does not match:

• Print Not Same and stop.

6.If all characters match:

• Print Same.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
void string_q5_compare() { string str1 = "Hello"; string str2 = "Hello"; bool areEqual = true; if(str1.length() != str2.length()) { areEqual = false; } else { for(int i = 0; i < str1.length(); i++) { if(str1[i] != str2[i]) { areEqual = false; break; } } } if(areEqual) { cout << "Strings are EQUAL" << endl; } else { cout << "Strings are NOT EQUAL" << endl; } }

Output Example

Input:
password123 password123
Output:
same

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next