#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    string target;
    string text;
    getline(cin, target);
    getline(cin, text);

    // 转换为小写字母,以便进行大小写不敏感的匹配
    transform(target.begin(), target.end(), target.begin(), ::tolower);
    transform(text.begin(), text.end(), text.begin(), ::tolower);

    int count = 0;
    int position = -1;
    
    size_t found = text.find(target);
    while (found != string::npos) {
        // 确保找到的单词是独立的,即前后字符不是字母
        if ((found == 0 || !isalpha(text[found - 1])) && (found + target.length() == text.length() || !isalpha(text[found + target.length()]))) {
            count++;
            if (position == -1) {
                position = found;
            }
        }
        found = text.find(target, found + 1);
    }

    if (count == 0) {
        cout << -1 << endl;
    } else {
        cout << count << " " << position << endl;
    }

    return 0;
}
C++代码实现单词查找功能:统计次数和第一次出现位置

原文地址: https://www.cveoy.top/t/topic/mrjD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录