C++ Program to Compare Two Strings

«
»

This is a C++ Program to Compare Two Given Strings for Equality.

Problem Description

The program takes two strings and checks for their equality.

Problem Solution

1. The program takes two strings.
2. Using string function, the two strings are compared.
3. The result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Compare Two Given Strings for Equality. The program output is shown below.

  1. #include<iostream.h>
  2. #include<string.h>
  3. using namespace std;
  4. int main ()
  5. {
  6.     char str1[50], str2[50];
  7.     cout<<"Enter string 1 : ";
  8.     gets(str1);
  9.     cout<<"Enter string 2 : ";
  10.     gets(str2);
  11.     if(strcmp(str1, str2)==0)
  12.         cout << "Strings are equal!";
  13.     else
  14.         cout << "Strings are not equal.";
  15.     return 0;
  16. }
Program Explanation

1. The user is asked to enter two strings and stored in ‘str1’ and ‘str2’.
2. Using an inbuilt function strcmp() under the library string.h, the two strings are compared for equality.
3. The result is then printed if they are equal are not.

advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter string 1 : hi
Enter string 2 : hello
Strings are not equal.
 
Case 2 :
Enter string 1 : 12345
Enter string 2 : 12345
Strings are equal!
 
Case 3 :
Enter string 1 : STRING
Enter string 2 : string
Strings are not equal.

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.