Well I have this task where I have to count how many times the string "hope" appears anywhere in the given string, except any letter for the 'p' is valid, so words like "hode" and "hooe" would count. Now I don't if took the best approach but my idea was to create a random string generator(which I did) and depending how long the string is, the third letter p would be replace by a random letter from a-z lowercase.
Here is an example: If the user would like the random string to be 9 characters long(whitespace included), it would look like this "hoxe hobe". The characters h, o, and e would remain the same but p will be always changing. The output would say that the word hope appeared two. Like I said, there's probably an easier way but this is method that I went by.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main ()
{
// An array of characters that is static and remains constant.
staticconstchar letters[]={"abcdefghijklmnopqrstuvwxyz"};
int n; // Loop counter
int i; /* Another counter that will dictate how many letters are
generated. */
string word; /* The string that will hold all the letters that are
generated. */
int stringLength = sizeof(letters) - 1; // The length of the string.
// Prompt the user.
cout << "How many letters would you like this string to generate? ";
cin >> i;
cout << endl;
while(i < 0) // Check to see if the number is negative.
{
cerr << "Error, no negative values. ";
cin >> i;
}
srand(time(NULL)); // Initializing a random seed.
for(n=0; n<i; n++)
{
// store the letters in this string.
word += letters[rand() % stringLength];
}
cout << "Random string: " << word << "\n"; // Display string.
return 0;
}
task: count how many times the string "hope" appears anywhere in the given string
solution: create a random string generator and depending how long the string is, the third letter p would be replace by a random letter
I'm not following.
The user enters "the quick brown fox hope over the lazy dog"
Your program should respond: 1
¿how are you using a random string generator to count?
Well I was thinking that the random string generator would only generate random letters for the third letter. This would force the program to constantly generate words like hoxe hobe hoqe etc. The problem is I'm having trouble figuring out how to force the program to do that. And no, the user doesn't enter anything like your example; they only enter numbers. The number dictates how long the string will be. For example if they enter 4, the output lohy. Now that I know the length of the string, I can use a for loop to count the number of times words like hoye hobe etc etc appear.