Write a function to compare two C-strings for equality. The function should return true if the strings are equal and false if they are not. Your function should ignore case, punctuation, and whitespace characters. Test your function with a variety of input strings.
Program:
//A sample program to test compare function of two strings
#include<iostream>
#include <string>
#include<cctype>
using namespace std;
bool compare(string s1,string s2);
//main function to test our compare function
int main()
{
string s1,s2;
cout<<"Enter two strings :"<<endl;
getline(cin,s1);
getline(cin,s2);
bool res=compare(s1,s2);
if(res)
cout<<"Two strings are equal";
else
cout<<"Two strins are not equal";
return 0;
}
//The function to compare two C-strings for equality
//ignore case, punctuation, and whitespace characters
bool compare(string s1,string s2)
{
int length1,length2,max;
length1=s1.length();
length2=s2.length();
if(length1>length2)
max=length1;
else
max=length2;
for(int i=0,j=0;i<max;i++,j++)
{
//check upto last character whether character is punctuation
//or white space in string1 and skip that character
while((ispunct(s1[i]) || isspace(s1[i])) && i<max)
i++;
//check upto last character whether character is punctuation
//or white space in string2 and skip that character
while((ispunct(s2[j]) || isspace(s2[j])) && j<max)
j++;
//if i or j value is greater than max length of strings break
if(i==max || j==max)
break;
//convert both characters of both stribgs to lower and compare
if(tolower(s1[i]) != tolower(s2[j]))
return false;
}
return true;
}
TEST CASE 1 OUTPUT:
Enter two strings :
j''''''''''''
j
Two strings are equal
TEST CASE 2 OUTPUT:
Enter two strings :
jkkkj
jkk'j
Two strins are not equal
TEST CASE 3 OUTPUT:
Enter two strings :
as's''s
asss
Two strings are equal