簡體   English   中英

在C ++中從字符串輸出元音和輔音

[英]Outputting vowels and consonants from strings in c++

這是我必須回答的問題:

Write a program that declares two strings: s1 and s2.

Initialize both of them using getline(cin, string) function.  

a)      Output the length of each string  
b)      Output the first appearance of a letter a in the first string  
c)      Output the first appearance of a letter b in the second string  
d)      Output the first word of each string  
e)      Output the last word of each string  
f)      Output first sentence reversed  
g)      Output second sentence with the words reversed ( the last word goes first, second last second, and so on)  
h)      Output the total number of vowels in the first sentence  
i)      Output the total number of consonants in the second sentence

這是我到目前為止的內容:

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM