String occurances?

Hey I'm a college student working on a C++ Project and I'm currently in a bit of a pinch. My project involves having a user input two strings. Once the user inputs two strings, they will be compared and the second string will be used to detect if it occurs in the first string (i.e. finding the second string in the first string) and then outputting the amount of times the string has occured. I've managed to get past the 'inputting strings' part, but I have no clue on how to find occurances within the first string. A little help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <string>

using namespace std;

int StringLong(char []);
int StringShort(char []);

int main()
{
	char firstinput[10000];
	int len;
	cout << "Welcome to my take on the CSCI Home Project." << endl;
	cout << "Please input your own first string: ";
	cin >> firstinput;
	char secondinput[10000];
	int len2;
	cout << "Please input your second string: ";
	cin >> secondinput;

	len = StringLong(firstinput);
	cout << "Length of first string = " << len << endl;
	len2 = StringShort(secondinput);
	cout << "Length of second string= " << len2 << endl;
	cout << endl;

    if (len2 > len)
    {
        cout << "ERROR: Your second string is longer than your first String. Restarting..." <<endl <<endl;
        return main();
    }
   else
   {
       return 0; (NOTE: THIS IS WHERE I AM TO START FINDING THE OCCURRENCES OF THE SECOND STRING IN THE FIRST STRING)
   }
}


int StringLong (char x[])

{
	int counter = 0;
	for (int index = 0; index < 10000; index++)
	{
		if (x[index] == '\0')
			break;
			counter ++;

	}
return counter;
}

int StringShort (char x[])

{
	int counter = 0;
	for (int index = 0; index < 10000; index++)
	{
		if (x[index] == '\0')
			break;
			counter ++;

	}
return counter;
}
Last edited on
See http://www.cplusplus.com/reference/cstring/strstr/
If it returns NULL, you have no occurrence. If not, you have at least one. If found, replace the string with an empty string, and continue searching. If found, you now have two occurrences. And so on. Use a do...while loop
Topic archived. No new replies allowed.