I want the user to enter a word and a sentence then I want my program to find the word in that text and cout's the position the word starts. I don't want my program to find a word in middle of another for example if the user enters "hi" I don't want the program to find it in "hive" so I figured out it should also find a space after the word if finds but how should I do so the program I wrote below was only thing occurred my mind so I would be grateful if you help me edit it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
int main ()
{
std::string str ;
std::getline (std::cin,str);
std::string str2 ;
std::getline (std::cin,str2);
std::size_t found = str2.find(str" ");
for (unsigned i=0; i<str.length(); ++i)
{ if (found!=std::string::npos)
std::cout << str.at(i);
}
return 0;
}
#include <iostream>
#include <string>
#include <cctype>
usingnamespace std;
//===============================================
string lower( string text )
{
for ( char &c : text ) c = tolower( c );
return text;
}
//===============================================
bool foundIt( string text, string toFind )
{
text = ' ' + text + ' '; // add a space at beginning and end
toFind = ' ' + toFind + ' ';
text = lower( text ); // work in a common case
toFind = lower( toFind );
return text.find( toFind ) != string::npos;
}
//===============================================
int main ()
{
string text, toFind;
cout << "Enter long text: "; getline( cin, text );
cout << "Enter bit to be found: "; getline( cin, toFind );
cout << '"' << toFind << '"' << ( foundIt( text, toFind ) ? " was " : " was not " ) << "found in " << '"' << text << '"' << '\n';
}
Enter long text: This is the winter of our discontent
Enter bit to be found: win
"win" was not found in "This is the winter of our discontent"
Enter long text: This is the winter of our discontent
Enter bit to be found: winter
"winter" was found in "This is the winter of our discontent"