In: Computer Science
in basic c++ program please!!
Write a word search and word count program.
For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life. 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.
(Hint: You need to use while loop, .find and .length function from string library. Also, you will need to use string::npos.)
C++ code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//String from which the words will be searched
string str = "For God so loved the world that he gave
his one and only Son, \
that whoever believes in him shall not perish but have
eternal life. \
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.";
cout<<"Enter String or phrase to be searched:\n";
string c;
//Taking word/phrase from user
getline(cin,c);
//Finding the index of word/phrase in the
string
size_t found = str.find(c);
int count=0;
//Loop till reaches end of the string
while (found != string::npos){
count++;
//Finding word/phrase from next index of the previous occurrence of
it.
found = str.find(c, found+1);
}
cout<<"The word/phrase "<<c<< " comes
"<<count<<" times."<<"\n";
return 0;
}
Output: