如何检查语句字符串是否包含 C++ 中的单词?

问题描述

我想在 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;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...