+ 1
Program for searching a word in a sentence.
Hi guys I needed a program using which I can search a word in a particular sentence. Can someone please give me the code or link . (Note language : c++)
3 Answers
+ 12
You can either use regular expressions for that like noname said or you can make your own function for it.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Welcome to the SoloLearn";
string sub = "SoloLearn";
int index = 0, count = 0;
bool isFound = false;
for(int i = 0; i < str.size(); i++)
{
if(str[i] == sub[index])
{
index++;
count++;
if(count == sub.size())
{
isFound = true;
break;
}
}
else
{
index = 0;
count = 0;
}
}
if(isFound)
cout << "Word found in the string\n";
else
cout << "Word not found in the string\n";
return 0;
}
+ 3
For this kind of problems , it's recommended to use regular expressions
https://www.geeksforgeeks.org/regex-regular-expression-in-c/
+ 2
Or you can use the find function:
auto pos = str.find(sub);
if(pos != string::npos)
cout << "Word found in the string\n";
else
cout << "Word not found in the string\n";
In the notation used by nAutAxH AhmAd