问题描述
我想在 C++ 中检查语句字符串是否包含单词。现在的问题是,在整个互联网上,他们使用 string::find 或 boost 库,但这些方法的问题在于它只检测没有空格的字符串中的单词,例如,如果我使用的是字符串:: find 方法不会检测到以下字符串中的happy 这个词:“I am happy”,但会检测到:“iamhappy” 那么有人知道怎么做吗?
解决方法
以下内容几乎是从 cpp reference string find 逐字逐句地截取的。它打印“找到:快乐”。
#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;
}