Google search "lambda function C++" or something, there's plenty of information. It's not just a C++ thing, but since you're presumably more comfortable with C++ than other languages it's probably easiest for you to learn lambda functions that way.
Oh, Im sorry!
I, accidentally, put the bool inside the constructor! So the code works now, but 1 last question: I thought that if you use the isalpha thing, only full words are being searched. But when I let the program look for the word "we", for example, the word well also gets listed. So why use isalpha then?
Sorry, that was a mistake/oversight on my part. This code works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
bool contains_word(const std::string& sentence, const std::string& word)
{
size_t pos = -1;
// Find the start of 'word' in 'sentence'.
while ((pos = sentence.find(word, pos + 1)) != std::string::npos) {
// Make sure it's actually a word (e.g. "rain" could be part of
// "drain"). isalpha checks if the given character is in the
// alphabet. Here we check if the characters before and after
// 'word' are alphabet characters. If neither of them is an
// alphabet character then we've found a whole word.
bool start = ((pos < 1) || !(isalpha(sentence[pos - 1])));
bool end = ((pos + word.size() > sentence.size() || !(isalpha(sentence[pos + word.size()]))));
if (start && end)
returntrue;
}
// If we get to here then we didn't find any instance of 'word' that was
// a whole word.
returnfalse;
}
isalpha() is a function which returns 1 (true) if the character you give it is in the alphabet. The variable bool start = ((pos < 1) || !(isalpha(sentence[pos - 1])));
is false if there is an alphabet character before the word, while the variable bool end = ((pos + word.size() > sentence.size() || !(isalpha(sentence[pos + word.size()]))));
is false if there is an alphabet character after the word. If both of them are true then it means that a whole word has been found, so the function returns true. If it can't find a match to "word" which is a whole word, it returns false.
Bare in mind that:
1. Since you're no longer doing it in a loop, it will only work if the first match is a whole word. What I mean is, without a loop, that function wouldn't find "rain" in the sentence "drain the rain" because the first match isn't a whole word, and it only looks at the first match. With a loop it looks at all matches.
2. You will get an error at sentence[pos - 1] if pos = 0 (because you'll be trying to access sentence[-1] which is not valid). This will be a problem any time the word is at the start of the sentence (like if you were searching for "hello" in "hello world").