Good day everyone! I have the codes for such a problem where, to create a program that counts how many times the second string appears on the first string. Here it is:

#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
    char first [100], second;
    int count;

    cout <<"Enter 1st String: ";
    cin.get (first, 100);

    cout <<"Enter 2nd String: ";
    cin >> second;

    for (int i = 0; i < strlen (first); i++)
    {
        if (tolower(first[i]) == tolower(second))
        {
                              count++;
                              }
                              }


    cout << "THE STRING " << "'" << second << "'" << " appeared " << count << " times in " << first << ".";

    getch ();
    return 0;
}

Hope anyone can help me. :(

Yes it counts if you put 1 letter only, but if you put 2, it is an error. As an example. If the first string is Harry Partear, and the second string is ar, it must count as 3.

Your algorithm is a little wrong. Here is how you can do it (pseudocode):

string first, second;
// get the data for the string
for i = 0 to i < first size - second size
    if (substring(first[i], first[i+second size]) == second)
        counter++;
Member Avatar for thendrluca

Try this.

int main ()
{
    char first[100];
    char second[100];
    int count;

    std::cout << "Enter 1st String: ";
    std::cin.get(first, 100);

    std::cout << "Enter 2nd String: ";
    std::cin.get(second, 100);

    char *substring = first;

    while ((substring = strstr(substring, second)) != NULL) count++;

    std::cout << "THE STRING " << "'" << second << "'" << " appeared " << count << " times in " << first << ".";

    return 0;
}

@NathanOliver : Using the data type string is prohibited by our professor, but thank you for taking a time to make a reply and reading my problem. :)

@thendrluca : Tried the codes that you have suggested bro, it prompts for first string, but I can't input for the second string. :(

Member Avatar for thendrluca

one moment please ))

Member Avatar for thendrluca

some changes

#include <iostream>
#include <string.h>

int main ()
{
    char first[100];
    char second[100];
    int count = 0;
    char *substring = first - 1;

    std::cout << "Enter 1st String: ";
    std::cin.getline(first, 100);

    std::cout << "Enter 2nd String: ";
    std::cin.getline(second, 100);

    while ((substring = strstr(substring + 1, second))) count++;

    std::cout << "THE STRING " << "'" << second << "'" << " appeared " << count << " times in " << first << ".";

    return 0;
}

@thendrluca : Thank you for taking your time in my problem dude. Have a Merry Christmas and a Happy New Year. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.