HI guys! So I have to create a word search and word count program. I inputted the text (I know that its long and kind of a weird way to put it but my instructor said it was fine) and then prompted the reader to enter a word or phrase. What I can't figure out though is how to search the string given by the user from the text I inputted and show how many times that word or phrase was found in the text. I started it but the while loops are so confusing to me. I need to use the while loop, .find and .length functions from the string library. Also, I need to use string::npos. I don't want you guys to just hand me the answer, I would actually like to understand what I am doing. Any help is greatly appreciated, thanks!
#include<iostream>
#include<string>
using namespace std;
int main() {
//USE WHILE LOOP, .FIND, .LENGTH, AND STRING::NPOS
//declare variables
const string bible = "For God did not send his Son into the world to condemn the world, but to save the world through him. Whoever believes in him is not condemned, but whoever does not believe stands condemned already because they have not believed in the name of God’s one and only Son. This is the verdict: Light has come into the world, but people loved darkness instead of light because their deeds were evil. Everyone who does evil hates the light, and will not come into the light for fear that their deeds will be exposed. 21 But whoever lives by the truth comes into the light, so that it may be seen plainly that what they have done has been done in the sight of God.";
string searchWord;
int count = 0;
//prompt the user
cout << "Please enter a word or phrase: " << endl;
getline(cin, searchWord);
//search the scripture for the user's word or phrase
while (bible.find(searchWord) != string::npos) { // Loop expression
count++; // Loop body: Sub-statements that execute if the expression evaluated to true
bible == bible.substr();
}
// Statements that execute after the expression evaluates to false
You can do it like this:
declare variables pos and startpos, count as size_t and initialize them to 0.
The you call bible.find(searchWord, startpos) to store the result in pos.
while pos != string::npos do
{
display result;
inc count by 1
inc startpos with the length of searchword + 1
call bible.find(searchWord, startpos)
}