我们先都转换成小写或者是大写可以用 来作为区分的标志每次读取到空格处然后分辨此时读取到的单词是否和所给的单词一致。具体看代码详解#include bits/stdc.h using namespace std; void tolower(string s) // 转化为小写 { for(int i 0; i s.size(); i) { if(s[i] A s[i] Z) s[i] 32; } } bool check(string a, string b) // 判断两字符串是否相等 { if(a.size() ! b.size()) return false; for(int i 0; i a.size(); i) { if(a[i] ! b[i]) return false; } return true; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string a, s; getline(cin, a); getline(cin, s); // 读取字符串 tolower(a); tolower(s); // 都变小写 int n s.size(), i 0; // 获取n 和 定义 指针 i int retpos -1, ret 0; // 最终结果存放 while(i n) { while(s[i] i n) i; // 先跳过空格 string tmp; // 当前单词的存放位置 int pos i; // 当前单词的起始位置 while(s[i] ! i n) // 开始读入单词 不是 就读入 { tmp s[i]; i; } if(check(tmp, a)) // 判断当前字符是否是想要的 { if(retpos -1) retpos pos; ret; } } if(retpos -1) // 一个没有 cout -1; else // 输出结果 cout ret retpos; return 0; }