In: Computer Science
Please write code in c++ using iostream library.
Write a function bool cmpr(char * s1, int SIZE1, char * s2, int
SIZE2) that compares two strings.
Input
Input contains two strings. Each string is on a separate line.
example:
aqua
aqua
Output
Output YES if given two strings are the same or NO otherwise.
YES
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.
#include<iostream.h>
#include<string.h>
using namespace std;
int main ()
{
char str1[50], str2[50];
cout<<"Enter string 1 : ";
gets(str1);
cout<<"Enter string 2 : ";
gets(str2);
if(strcmp(str1, str2)==0)
cout << "Strings are equal!";
else
cout << "Strings are not equal.";
return 0;
}
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.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
/* C++ Program to Compare Two Strings without using strcmp */ #include<iostream> #include<string.h> using namespace std; int main() { char str1[50],str2[50],i=0,j=0,flag=0; cout<<"\nEnter first string :: "; gets(str1); cout<<"\nEnter Second string :: "; gets(str2); while(str1[i]!='\0') { i++; } while(str2[j]!='\0') { j++; } if(i!=j) { flag=0; } else { for(i=0,j=0;str1[i]!='\0',str2[j]!='\0';i++,j++) { if(str1[i]==str2[j]) { flag=1; } } } if(flag==0) { cout<<"\nStrings are not equal.\n"; } else { cout<<"\nStrings are equal.\n"; } return 0; } |