You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C++程序检测输入字符串中是否包含特定关键词?

C++聊天机器人关键词包含检测解决方案

1. 解决完整输入问题

你当前使用cin >> ans只能读取到第一个空格前的内容,比如输入"hello there"时,ans只会存储"hello",导致后续检测无法覆盖整句输入。要读取包含空格的整行内容,需要改用getline(cin, ans)。

2. 检测字符串中的关键词

C++的std::string类提供了find方法,可用于查找子字符串的位置:

  • 若ans.find("hello")的返回值不等于string::npos,则说明ans中包含"hello"关键词。

完整示例代码

#include <iostream>
#include <string>
using namespace std;

int main() {
    string ans;

    cout << "Hello, I am Oliver, a Chatbot" << endl;
    cout << "What can I do for you today?" << endl;
    // 读取整行输入,包含空格
    getline(cin, ans);

    // 检测是否包含"hello"关键词
    if (ans.find("hello") != string::npos) {
        cout << "Hello to you too!" << endl;
    } else {
        cout << "I don't understand that." << endl;
    }

    return 0;
}

进阶:忽略大小写匹配

如果需要识别"Hello"、"HELLO"这类不同大小写的输入,可以先把输入字符串统一转换为小写,再进行检测:

#include <iostream>
#include <string>
#include <cctype> // 用于tolower函数
using namespace std;

int main() {
    string ans;

    cout << "Hello, I am Oliver, a Chatbot" << endl;
    cout << "What can I do for you today?" << endl;
    getline(cin, ans);

    // 将输入转换为全小写
    for (char &c : ans) {
        c = tolower(static_cast<unsigned char>(c));
    }

    if (ans.find("hello") != string::npos) {
        cout << "Hello to you too!" << endl;
    } else {
        cout << "I don't understand that." << endl;
    }

    return 0;
}

内容的提问来源于stack exchange,提问作者bleachedb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:30:41