如何分离被...连接的单词、统计元音并筛选符合k值的单词
问题需求
读取文本内容,文本中存在类似her...closet的内容(这类内容会被当作单个“单词”读取),需要将其拆分为独立单词;统计每个单词的元音数量,若元音数≥给定值k,则输出该单词。
示例输入:
2 Maria has two apples in her...closet
示例输出:
Maria apples closet
现有C++代码
#include <iostream> #include <fstream> #include <cstring> using namespace std; int is_letter(char s) { if (('a' <= s && s <= 'z') || ('A' <= s && s <= 'Z')) { return 1; } return 0; } int main(){ ifstream fin("date.in"); const int LIM = 261; const int LIMV = 11; char vowals[LIMV] = "aeiouAEIOU"; char s[LIM]; int k; cin >> k; while (fin >> s) { int found_letter = 1; int nrVowels = 0; int letter = -1; int n = strlen(s); for(int i = 0; i < n; ++i) { if(is_letter(s[i])) { ++letter; found_letter = 1; if (strchr(vowals,s[i])) ++nrVowels; } else { found_letter = 0; letter = -1; } } for (int i = 0; i <= letter; ++i) { if(nrVowels >= k && found_letter == 1) { cout << s[i]; } } cout <<"\n"; } return 0; }
个人思路与当前问题
- 思路:每次找到字母时维护计数器,判断是否为元音并统计数量;遇到非字母时重置计数器,最终若元音数≥k且为有效单词则输出。
- 当前问题:无法正确拆分出独立的单词。
修复方案
原代码的问题在于,仅处理了字符串中最后一段连续字母序列,完全忽略了非字母分隔符前的单词。需要调整逻辑,遍历字符串时实时维护当前正在构建的单词及其元音计数,遇到非字母时立即检查并输出符合条件的当前单词,遍历结束后还要处理最后一段字母序列。
修改后的代码如下:
#include <iostream> #include <fstream> #include <cstring> using namespace std; // 判断是否为字母 int is_letter(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } // 判断是否为元音 int is_vowel(char c) { const char vowels[] = "aeiouAEIOU"; return strchr(vowels, c) != nullptr; } int main() { ifstream fin("date.in"); const int LIM = 261; char s[LIM]; int k; cin >> k; while (fin >> s) { char current_word[LIM] = {0}; int current_vowels = 0; int word_len = 0; int n = strlen(s); for (int i = 0; i < n; ++i) { if (is_letter(s[i])) { // 积累当前单词的字符 current_word[word_len++] = s[i]; // 统计元音数量 if (is_vowel(s[i])) { current_vowels++; } } else { // 遇到非字母,检查当前积累的单词是否符合输出条件 if (word_len > 0 && current_vowels >= k) { cout << current_word << endl; } // 重置当前单词的状态 memset(current_word, 0, sizeof(current_word)); word_len = 0; current_vowels = 0; } } // 处理字符串末尾的最后一段单词 if (word_len > 0 && current_vowels >= k) { cout << current_word << endl; } } return 0; }
关键修改点
- 新增
is_vowel函数,单独封装元音判断逻辑,代码更清晰 - 遍历字符串时实时构建当前单词,并同步统计元音数量
- 遇到非字母字符时,立即检查并输出符合条件的当前单词,随后重置状态
- 遍历结束后单独处理最后一段连续字母组成的单词
这样就能正确拆分her...closet为her和closet,各自统计元音数:her有1个元音(小于k=2,不输出),closet有2个元音(等于k=2,输出),结合其他单词即可得到符合要求的输出结果。
内容的提问来源于stack exchange,提问作者popescubianca
相关产品推荐
相关产品推荐

