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

This C++ program reads two Strings (String1 and String2) and checks whether String2 can be formed from String1, by printing ‘Yes’ otherwise ‘No’.
Submitted by Abhishek Jain, on June 11, 2017

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).

Example - 1

String1: IncludeHelp
Output:- Yes.

Yes,String2 can be formed from String1.

Example - 2

String1: IncludeHelp
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++

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')*/ 
	//same as 

	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(ans)                     //By default it checks: if(ans!=false)
	return 0;


Enter string1:IncludeHelp
Enter String2:Help

Related Programs


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.