SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Strings
Exercise:
Programming Projects
Question:9 | ISBN:9780132846813 | Edition: 5

Question

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.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.