V. Write a C++ program that Prompts the user to enter two strings (use char arra
ID: 3545770 • Letter: V
Question
V. Write a C++ program that
Prompts the user to enter two strings (use char arrays to store the two strings in your program)
o Str1: Length of string one should be <= 11 characters
o Str2: Length of string two should be <= 3 characters
NOTE: if the user enters 12 or more characters, for Str1 than your program should read ONLY the first 11 characters (see SAMPLE RUN 2), or prompt the user to re-enter the string (see ALTERNATE SAMPLE RUN 2 below).
Similarly, if the user enters 4 or more characters, for Str2 than your program should read ONLY the first 3 characters, or prompt the user to re-enter the string.
Then your program should count the occurrences in the first string1 Str1, of the characters in the second second string, Str2.
o If Str1 = "abracadabra" and Str2 = "bax"
b from bax occurs 2 times in abracadabra
a from bax occurs 5 times in abracadabra
x from from bax occurs 0 times in abracadabra
o Thus the count would be 7
DO NOT WORRY about repeats of chars in Str2
Explanation / Answer
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,j, cnt;
char str1[12], ch;
char str2[4];
int alphabets[128];
for(i=0;i<128;i++)
{alphabets[i]=0;}
cout<<"Enter two strings ";
cout<<"Enter String1 (max 11 characters) : ";
cin>>str1;
cnt=0;
for(i=0;str1[i]!='';i++)
{cnt++;}
if(cnt>11)
{
cout<<"String1 must have a maximum of 11 characters ";
cout<<"Enter String1 (max 11 characters) : ";
cin>>str1;
cnt=0;
for(i=0;str1[i]!='';i++)
{cnt++;}
}
cout<<"Enter String2 (max 3 characters) : ";
cin>>str2;
cnt=0;
for(i=0;str2[i]!='';i++)
{cnt++;}
if(cnt>3)
{
cout<<"String2 must have a maximum of 3 characters ";
cout<<"Enter String2 (max 3 characters) : ";
cin>>str2;
cnt=0;
for(i=0;str2[i]!='';i++)
{cnt++;}
}
cnt = 0;
for(i=0;str2[i]!='';i++)
{
for(j=0;str1[j]!='';j++)
{
if(str1[j] == str2[i] && alphabets[str2[i]] == 0)
{
cnt++;
}
}
alphabets[str2[i]]=1;
}
cout<<"The number of occurences of string2 characters in string1 = "<<cnt<<" ";
return 0;
}
This is the required program to print the occurences of the strings2 in string1.
As mentioned in the problem statement, this code prompts the user if the input is more than maximum characters.
Hope, this helps you, If you have any more doubts just comment and I can help you.
Cheers!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.