Home »
C++ programs »
C++ Most popular & searched programs
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 [Last updated : February 27, 2023]
Checking 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).
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.
C++ code to check whether a string2 can be formed from string1
#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