How to compare two strings for equality
IsEqual() takes two strings as an input parameter and it returns false if both the strings are not equal and returns true in case if both the strings are exactly equal.
Examples
If first string is “Google”, and
Second string is “Microsoft”, then it will return false because both strings are not equal.
If first string is “SAAD BIN SAULAT”, and
Second string is “saad bin saulat”, then it will also return false because both strings are not exactly equal- first string is in uppercase and the second string is in lowercase .
If first string is “Saad Bin Saulat”, and
Second string is “Saad Bin Saulat”, then it will return true because now both the strings are equal.
Summary of IsEqual()
First of all both the strings are checked that for length. If they are not equal in length then simply the function returns false indicating that the strings are not equal – this is used to simplify the number of comparison which should not be done in most of the cases when the strings are not equal in length. Then by only comparing the lengths it is determined that strings are not equal.
But in case if both the strings are equal in length, then element by element comparison is needed in order to determine its equality.
Code of IsEqual()
bool IsEqual( char * str1 , char * str2 )
{
if ( strlen( str1 ) != strlen( str2 ) )
return false;
else
{
for ( int i = 0; i < strlen(str1); i++)
{
if ( str1[i] != str2[i] )
return false;
}
}
return true;
}
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
bool IsEqual( char * str1 , char * str2 )
{
if ( strlen( str1 ) != strlen( str2 ) )
return false;
else
{
for ( int i = 0; i < strlen(str1); i++)
{
if ( str1[i] != str2[i] )
return false;
}
}
return true;
}
int main()
{
cout << IsEqual( "Saad Bin Saulat" , "Saad Bin Saulat" ) << endl;
cout << IsEqual( "Saad" , "Saad Bin Saulat" ) << endl;
cout << IsEqual( "Saad Bin Saulat" , "Saad" ) << endl;
cout << IsEqual( " Saad Bin Saulat " , " Saad Bin Saulat " ) << endl;
_getche();
return 0;
}
Output
1
0
0
1
0 comments:
Post a Comment