Answer to Question #265661 in C++ for 1vvo

Question #265661

Write a program for:

Searching a word present in a sentence or not, if present print its location with a successful note.


1
Expert's answer
2021-11-13T23:51:08-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS