Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

V. Write a C++ program that Prompts the user to enter two strings (use char arra

ID: 3545769 • 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>

using namespace std;

int main()
{
    char str1[12];
    char str2[4];
    int count = 0;

    cout << "Enter first string: ";
    cin.getline(str1, 12);
    if (cin.fail())
    {
        cin.clear();
        cin.ignore(100, ' ');
    }
    cout << "First string is: " << str1 << endl;

    cout << "Enter second string: ";
    cin.getline(str2, 4);
    cout << "Second string is: " << str2 << endl;

    for (int i = 0; str2[i]; ++i)
    {
        int occur = 0;
        for (int j = 0; str1[j]; ++j)
            if (str1[j] == str2[i])
                ++occur;
        count += occur;
    }
    cout << "Count: " << count << endl;

    return 0;
}