This is the C++ tutorial where we will write a C++ program to compare two strings. If you want to learn more about string in C++, click the link below.
We will compare two strings in two ways:
- Compare using strcmp() Function
- Compare two strings without using strcmp() function
C++ Program to Compare Two Strings
Both of the programs below take user input for the two strings that are to compare. Although to take input from the user you can use gets(str)
function that will take the string input with spaces in it.
The following program uses cin>>
method to take a string input. It only takes a single word.
1. C++ Program to compare two strings without using strcmp()
This program compare string in C++ without using strcmp() function. We sill use while loop to iterate through the string and inside while loop if loop is used to see if every letter is equal or not on both of the string.
If it is not equal then the if statement is executed and a flag variable will raise to 1 and the execution control comes out of the loop with the use of break statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; int main() { char str1[50], str2[50]; int i = 0, flag = 0; cout << "Enter the first string: "; cin >> str1; cout << "Enter the second string: "; cin >> str2; while (str1[i] != '\0' || str2[i] != '\0') { if (str1[i] != str2[i]) //if string are not equal { flag = 1; break; } i++; } if (flag == 0) cout << "\nStrings are Equal."; else cout << "\nStrings are not Equal."; return 0; } |
Output:
Enter the first string: simple2code
Enter the second string: simple2code
Strings are Equal.
2. C++ Program to compare two strings using strcmp()
The following program compare string in C++ using strcmp() function that is provided in the C++ library. This inbuilt function is defined under string.h
header file. Hence, it is necessary to include this file in the program at the beginning.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> #include <string.h> using namespace std; int main() { char str1[50], str2[50]; cout << "Enter the first string: "; cin >> str1; cout << "Enter the second string: "; cin >> str2; if (strcmp(str1, str2) == 0) cout << "\nStrings are Equal."; else cout << "\nStrings are not Equal."; return 0; } |
Output:
Enter the first string: coding
Enter the second string: coding
Strings are Equal.
Enter the first string: coding
Enter the second string: Coding
Strings are not Equal.
As you can see, the comparison on both of the programs are also case sensitive, the word “coding” is not equal to the word “coding”. Since the first letter is a lower letter in one string and capital on another.