数每个单词的元音
Count the vowels of every word
本文关键字:单词 更新时间:2023-10-16
我必须计算给定文本中 evey 单词的元音。我的尝试 :
#include <iostream>
#include <string.h>
using namespace std;
char s[255], *p, x[50][30];
int c;
int main()
{
cin.get(s, 255);
cin.get();
p = strtok(s, "?.,;");
int n = 0;
while (p)
{
n++;
strcpy(x[n], p);
p = strtok(NULL, "?.,;");
}
for (int i = 1; i <= n; i++)
{
c = 0;
for (int j = 0; j < strlen(x[i]); j++)
if (strchr("aeiouAEIOU", x[i][j]))
c++;
cout << c << " ";
}
return 0;
}
PS:我知道我的代码是C和C++的混合,但这是我在学校学到的。
案例在注释中关闭。
然而,为了好玩,我向你推荐了另一种变体,避免使用可怕的strtok()
,不需要有风险的strcpy()
,并且每个输入字符只处理一个。
由于您受老师的混合风格的约束,并且显然还不应该使用 c++ 字符串,因此我也尊重此约束:
const char separators[]=" t?.,;:"; // I could put them in the code directly
const char vowels[]="aeiouyAEIOUY"; // but it's for easy maintenance
int vowel_count=0, word_count=0;
bool new_word=true;
char *p=s;
cout << "Vowels in each word: ";
do {
if (*p==' ' || strchr(separators,*p)) {
if (!new_word) { // here, we've reached the end of a word
word_count++;
cout << vowel_count << " ";
vowel_count = 0;
new_word=true;
} // else it's still a new word since consecutive separators
}
else { // here we are processing real chars of a word
new_word=false; // we have at least on char in our word
if (strchr(vowels, *p))
vowel_count++;
}
} while (*p++); // It's a do-while so not to repeat the printing at exit of loop
cout << endl<<"Words: "<<word_count<<endl;
演示
这是我的解决方案:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char s[255];
int n,i,counter=0;
cin.get(s,255);
for(i=0; i<=strlen(s)-1; i++)
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u') counter++;
cout<<counter;
return 0;
}
如果你有一个元音(a,e,i,o或u(,你正在加到计数器。 您也可以使用 strchr,但这是一种更简单、更易于理解的方法。
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 当您在此单词中搜索单词时调整字符数组的大小?
- 数每个单词的元音
- 我们如何在文本文件中找到C++中的几个单词?
- 使用 BFS 的单词梯 2
- 替换字符串中的单词,但忽略引号中的单词