Q:

C++ program to check whether a string2 can be formed from string1

0

C++ program to check whether a string2 can be formed from string1

In general, a string (string 2) can be formed from another string (string 1) if string1 can contain all the characters of string2 (Repetition and Case sensitivity are also considered).

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example - 1

String1: IncludeHelp
String2:Help
Output:- Yes.

Yes,String2 can be formed from String1.

Example - 2

String1: IncludeHelp
String2:Helll
Output:- No

No, because ‘l’ comes 3 times in ‘Helll’ while there is only two ‘l’ present in IncludeHelp.

Example - 3

String1: IncludeHelp
String2: Hi
Output:- No

No, ‘i’ is in lower case in String2 while in String1, ‘I’ is in upper case (Case sensitive).

Hope you get all the points to be considered through above Examples.

Now come to the program, for faster and effective result we use concept of Count Array.

To learn about Count Array (implementation and use) go through the program C++ program to find the frequency of a character in a string using Count Array.

Program to check whether a string2 can be formed from string1 in C++

#include<iostream>
#include<cstring>
using namespace std;

int main()
{ 

	string s1,s2;

	cout<<"Enter string1:";
	cin>>s1;                  //input string 1

	cout<<"Enter String2:"; 
	cin>>s2;                  //input string 2

	/* intialize two count Arrays(count1,count2) 
		of size 58(A(65)-z(122)) with 0;*/  
	int i,count1[58]={0},count2[58]={0};      

	bool ans=true;

   /*count1[] increment at index equal to Each  
	character ASCII value subtracted by 65(ACSII of 'A')*/ 
	for(i=0;i<s1.size();i++)    
	   count1[s1[i]-'A']++;             
   
	//same as 
	for(i=0;i<s2.size();i++)
	   count2[s2[i]-'A']++;  

	for(int i=0;i<58;i++)
	{
		/* it checks for no. of characters in string1 and string2.
		 If frequency of any character in count2
		  exceeds count1 then it will assign 
		  ans as 'false' and break the loop.*/  		
		if(count1[i]<count2[i])           
		{
			ans=false;
			break;
		}
	}
	if(ans)                     //By default it checks: if(ans!=false)
		cout<<"Yes"<<endl;
	else
		cout<<"No"<<endl;
	
	return 0;
}

Output

Enter string1:IncludeHelp
Enter String2:Help
Yes

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to convert number to word (up to four ... >>
<< C++ program to print a spiral matrix...