在 c++ 中从字符串中输出元音和辅音

Outputting vowels and consonants from strings in c++

本文关键字:字符串 c++ 输出      更新时间:2023-10-16

这是我必须回答的问题:

编写一个声明两个字符串的程序:s1 和 s2。 使用 getline(cin, string( 函数初始化它们。  a( 输出每个字符串的长度  b( 输出第一个字符串中字母 a 的首次出现  c( 输出第二个字符串中字母 b 的第一次出现  d( 输出每个字符串的第一个单词  e( 输出每个字符串的最后一个单词  f( 输出第一句颠倒  g( 输出单词颠倒的第二句(最后一个单词先行,倒数第二个,依此类推(  h( 输出第一句中的元音总数  i( 输出第二句中的辅音总数

这是我到目前为止所拥有的:

#include <iostream>
#include <string>
using namespace std;     
int main()  {
string s1,s2,s3;
int blank = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int s2temp = 0;
cout << "enter two sentences" <<endl;
getline (cin, s1);
getline (cin, s2);
s3=s2;
// a
cout << "the length of the first string is " << s1.length() << endl;
cout << "the length of the second string is " << s2.length() << endl;
// b
cout<<"the first appearance of the letter 'A' in the first string is ";
cout << s1.find("a");
cout <<endl;
// c
cout<<"the first appearance of the letter 'B' in the second string is ";
cout << s2.find("b");
cout <<endl;
// d
int s1_first = s1.find(" ");
int s2_first = s2.find(" ");
cout << "the first word in the first string is " << s1.substr(0,s1_first) <<endl;
cout << "the first word in the second string is " << s2.substr(0,s2_first) <<endl;
// e
cout << "the last word in the first string is " << s1.substr(s1.find_last_of(" "), s1.length()-1) <<endl;
cout << "the last word in the second string is " << s2.substr(s2.find_last_of(" "), s2.length()-1) <<endl;
// f
for(int i = s1.length()-1; i >= 0; i--)
cout <<s1.substr (i,1)<<endl;
// g
return 0;
}

我已经为ghi尝试了几种不同的东西,但没有一个奏效,所以我想我会寻求帮助。

计算元音的一种方法是制作一个包含元音的字符串:

static const std::string vowels = "aeiouAEIOU";

接下来,对于字符串中的每个字符,在元音字符串中搜索它:

unsigned int vowel_count = 0;
const size_t length = text.length();
for (unsigned int i = 0; i < length; ++i)
{
const char c = text[i];
if (vowels.find(c) != std::string::npos)
{
++vowel_count;
}
}

这也可以应用于辅音。

对于那些不允许使用std::string的人,可以修改代码。

另一种方法是使用std::map.