+ 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++)

2nd Nov 2018, 4:21 PM
Ansh Sarkar
Ansh Sarkar - avatar
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; }
2nd Nov 2018, 4:57 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
For this kind of problems , it's recommended to use regular expressions https://www.geeksforgeeks.org/regex-regular-expression-in-c/
2nd Nov 2018, 4:26 PM
voidneo
+ 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
2nd Nov 2018, 8:57 PM
Leif
Leif - avatar