I want to check in C++ if a statement string contains a word. Now the problem is that all over the internet they use string::find or the boost library but the problem with these methods is that it only detect the word in a string with no spaces so for example, if i am using the string::find method it will not detect the word happy in the following string: " I am happy" but it will detect it in: "iamhappy" so does anyone know how to do it ?
Asked
Active
Viewed 1,818 times
0
-
You could try to tokenize your string with spaces and run find over each token. – L.S. Mar 22 '21 at 11:23
-
2No, `string::find` will also find "happy" in " I am happy". If it didn't, you made some kind of mistake. You can either tokenize the string (`std::istringstream` is a good friend to have), or use `find` and examine the characters before and after each hit, or use a regular expression. – molbdnilo Mar 22 '21 at 11:31
-
Not sure what you're doing, but finding "happy" in "I am happy" works fine for me. https://ideone.com/BE7tn8 Consider adding a [mcve] to your question that explains what you're doing and perhaps we can help. – Retired Ninja Mar 22 '21 at 11:34
-
It works for me (as expected), as you can see [here](https://godbolt.org/z/xGjPT5sbz). `std::string::find()` works even with spaces, spaces are just regular characters like others. You should have make a mistake (as @molbdnilo mentioned) – Fareanor Mar 22 '21 at 11:34
1 Answers
2
The following is taken almost verbatim from cpp reference string find. It prints "found: happy".
#include <iostream>
#include <string>
void print(std::string::size_type n, std::string const &s)
{
if (n == std::string::npos) {
std::cout << "not found\n";
} else {
std::cout << "found: " << s.substr(n) << '\n';
}
}
int main(int, char**){
const std::string s = "i am happy";
auto n = s.find("happy");
print(n, s);
return 0;
}

systemcpro
- 856
- 1
- 7
- 15
-
Good example, but there's a bit of a flaw in it. If the input string was "i am happy now" the output would be "happy now" and not just "happy". That might not matter, depending on the application. +1. – Pete Becker Mar 22 '21 at 13:34
-
@Pete Becker. That is true but if I am looking for a string "happy" then if I find it I have the string "happy". There is no need to extract the sub-string from the original string. We know what it is, it's the string we were searching for, "happy". The print was just for demo. We just check the return value of find and if successful we have both the position of the sub-string and the sub-string, namely the string we were searching for. – systemcpro Mar 22 '21 at 13:50