Count String in a String Using Datatype Char

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. 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. Here's the code:

#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. :(
Last edited on
You have that incorrect behaviour because "second" is declared as a simple char and not a char array.
Also, since you are using C++, why don't you switch to the string data type?
Last edited on
Our professor asked as to not use string types rather char type. And I already tried this new codes:

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

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

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

But the new problem is that, the program doesn't prompt the user to input the second string. :(
For the input, you can do like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

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

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

    cout <<"Enter 2nd String: ";
    cin.get(second, 100);
    
    cout << "First string: " << first << endl;
    cout << "Second string: " << second << endl;

    return 0;
}
Last edited on
Thank you for the help, it does prompts the user to input the second string. But, after putting the second string, and error appears where the cmd is not working or stopped working. :(
With my code? I just checked and everything is ok...
I see, you didn't get what I wanted to get out from my program. But thanks for the time. :)
Oh yes I know, but I did not want to write all the code for you! I just wanted to show how you can take two strings in input. Then the part of "counting the repetitions" is up to you...
Topic archived. No new replies allowed.