摘要:需要在文章中查找特定单词的出现次数和第一次出现的位置。匹配条件:不区分大小写,且必须是独立单词完全匹配。
详细解析
问题理解:
需要在文章中查找特定单词的出现次数和第一次出现的位置。匹配条件:不区分大小写,且必须是独立单词完全匹配。输入处理:
第一行输入目标单词,转换为小写。第二行输入文章,按空格分割成单词,并记录每个单词的起始位置。分割单词与位置记录:
遍历文章字符串,跳过空格,记录每个单词的起始位置和结束位置。将每个单词转换为小写,以便后续比较。统计与输出:
遍历分割后的单词列表,统计匹配次数并记录第一次出现的位置。根据统计结果输出相应格式。参考代码
#includeusingnamespacestd;
intmain{
string target, article;
getline(cin, target);
getline(cin, article);
// 将目标单词转为小写
transform(target.begin, target.end, target.begin, ::tolower);
vector
> words; // 存储单词的小写形式及其起始位置
int n = article.length;
for (int i = 0; i < n;) {
// 跳过空格
while (i < n && article[i] == ' ') i++;
if (i >= n) break;
int start = i; // 记录单词起始位置
// 找到单词的结束位置
while (i < n && article[i] != ' ') i++;
string word = article.substr(start, i - start);
// 转换为小写
transform(word.begin, word.end, word.begin, ::tolower);
words.push_back({word, start});
}
int count = 0;
int first_pos = -1;
for (constauto& p : words) {
if (p.first == target) {
count++;
if (first_pos == -1) {
first_pos = p.second;
}
}
}
if (count > 0) {
cout << count << " " << first_pos << endl;
} else {
cout << -1 << endl;
}
return0;
}
代码解释
统一大小写:
使用 transform 函数将目标单词和文章中的每个单词转为小写,确保匹配时不区分大小写。分割单词与记录位置:
遍历文章字符串,通过跳过空格找到每个单词的起始位置,并截取单词。将每个单词的小写形式及其起始位置存入 vector 中。统计匹配结果:
遍历存储的单词列表,统计与目标单词匹配的次数,并记录第一次出现的位置。输出结果:
根据匹配次数输出次数和位置,或输出 -1。示例测试
输入 #1:
Toto be or not to be is a question
处理过程:
目标单词转为小写后为 to。文章分割后的单词列表为 {"to", "be", "or", "not", "to", "be", ...},起始位置分别为 0, 3, 6, 9, 13, 16, ...。匹配到两次 to,第一次位置为 0。输出 #1:
2 0输入 #2:
toDid the Ottoman Empire lose its power at that time
处理过程:
目标单词为 to。文章中的单词均不匹配 to,故输出 -1。输出 #2:
-1关键点总结
大小写处理:统一转为小写确保不区分大小写。单词分割:正确分割空格,记录起始位置。完全匹配:确保单词是独立存在的,而非其他单词的一部分。来源:轩诚教育