In a C++ code, I'm trying to search for a word in a sentence but it keeps doing partial search. I want it to search only for the complete word not parts of it too, any help?
size_t kk;
string word="spo";
string sentence="seven spoons";
kk=sentence.find(word);
if (kk !=string::npos)
cout << "something" << endl;
Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.
To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.
To check if a string contains given substring, iterate over the indices of this string and check if there is match with the substring from this index of the string in each iteration. If there is a match, then the substring is present in this string.
Check if a string contains a sub-string in C++ This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches. If the item is found, this function returns the position. But if it is not found, it will return string::npos.
It sounds like what you want is handled by the concept of word boundaries or word characters in regular expressions.
Here's a program that will return only a complete match. That is, it will only return a word if that word completely matches the exact word you're searching for. If some word in sentence
has your target word as a strict substring then it will not be returned.
#include <regex>
#include <string>
#include <iostream>
int main() {
std::string word = "spo"; // spo is a word?
std::string sentence = "seven spoons";
std::regex r("\\b" + word + "\\b"); // the pattern \b matches a word boundary
std::smatch m;
if (std::regex_search(sentence, m, r)) { // this won't find anything because 'spoons' is not the word you're searching for
std::cout << "match 1: " << m.str() << '\n';
}
sentence = "what does the word 'spo' mean?";
if (std::regex_search(sentence, m, r)) { // this does find the word 'spo'
std::cout << "match 2: " << m.str() << '\n';
}
}
Or alternatively maybe you mean you want to find any word that matches a partial word you're searching for. regex can do that as well:
std::string partial_word = "spo";
std::regex r("\\w*" + partial_word + "\\w*"); // the pattern \w matches a word character
This produces:
match 1: spoons
match 2: spo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With