Write a program for:
Searching a word present in a sentence or not, if present print its location with a successful note.
#include<iostream>
#include<string>
using namespace std;
int FindWord(string sentence, string word);
int main()
{
string sentence = "When we talk about such actions or situations, we need to use simple present tense";
string word = "use";
if (FindWord(sentence, word) != -1)
{
cout << "Word \"" << word << "\" has been found at position " << FindWord(sentence, word);
}
else
{
cout << "Word \"" << word << "\" wasn't found";
}
}
int FindWord(string sentence, string word)
{
int loc = -1;
for (int i = 0; i < sentence.size(); i++)
{
if (sentence[i] == word[0])
{
loc = i;
for (int j = 0; j < word.size(); j++,i++)
{
if (sentence[i] != word[j])
{
i = loc;
loc = -1;
break;
}
}
}
if (loc != -1)break;
}
return loc;
}
Comments
Leave a comment