文本查找指定单词

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

int main()
{
    string aim, s;
    // 读取目标单词
    cin >> aim;
    cin.ignore(); // 吃掉换行!重要
    // 读取整行文章(包含空格)
    getline(cin, s);

    // 全部转小写,方便对比
    string aim_low;
    for (char c : aim)
        aim_low += tolower(c);
    
    int cnt = 0;
    int first_pos = -1;
    int n = s.size();

    for (int i = 0; i < n; )
    {
        // 跳过空格
        if (s[i] == ' ')
        {
            i++;
            continue;
        }
        // 找到一个单词的起始位置
        int start = i;
        string word_low;
        // 取出整个单词直到遇到空格
        while (i < n && s[i] != ' ')
        {
            word_low += tolower(s[i]);
            i++;
        }
        // 判断单词相等
        if (word_low == aim_low)
        {
            cnt++;
            if (first_pos == -1)
                first_pos = start;
        }
    }

    if (cnt == 0)
        cout << -1 << endl;
    else
        cout << cnt << " " << first_pos << endl;

    return 0;
}
posted @ 2026-10-22 23:52  yi_one  阅读(7)  评论(0)    收藏  举报