从字符串"Hello, have a good day"中删除所有辅音

delete all consonents from the string "Hello, have a good day"

本文关键字:删除 day good Hello 字符串 have      更新时间:2023-10-16

我已经看到很多很好的代码来解决这个问题。我是编码新手。我的问题是我的逻辑哪里出了问题。 我认为问题出在第二个字符串 str1 上。我不敢初始化它。即使我正在逐个元素打印 if ,它仍在工作。但是当我尝试打印整个字符串 str1 时,它不起作用。

#include<iostream>
#include<string>

using namespace std;

int main()
{
 string str = "Hello, have a good day", str1;


 for (int i = 0, j =0; i < str.length(); ++i)
 {

    if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
        if (str[i] == 'I' || str[i] == 'i' || str[i] == 'U' || str[i] == 'u' || str[i] == 'O' || str[i] == 'o' || 
            str[i] == 'A' || str[i] == 'a' || str[i] == 'E' || str[i] == 'e' )
        {
            str1[j] = str[i];
            //std::cout << str1[j] ;
            j++;
        }
    else 
    {
        str1[j] = str[i];
        j++;
    }   
 }
 cout << str1 <<'n';

}

输出只是空白。

首先要做的是编写一个函数来确定一个字符是否是辅音:

bool is_not_consonant(char ch) {
    static char consonants[] = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return std::find(std::begin(consonants), std::end(consonants), ch) == std::end(consonants);
}

然后将该函数用作谓词来std::copy_if

std::string result;
std::string input = whatever;
std::copy_if(std::begin(input), std::end(input),
    std::back_inserter(result),
    is_not_consonant);

解释

问题是你不需要 else 条件。您需要做的就是检查元音,如果找到的元音,则打印在您的 if 条件下正确覆盖的元音。

法典

试试这个:

#include<string>
using namespace std;
int main()
{
    string str = "Hello, have a good day", str1;
    for (int i = 0; i < str.length(); ++i)
    {
        if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
            if (str[i] == 'I' || str[i] == 'i' || str[i] == 'U' || str[i] == 'u' || str[i] == 'O' || str[i] == 'o' || str[i] == 'A' || str[i] == 'a' || str[i] == 'E' || str[i] == 'e' )
            {
                str1 += str[i];
            }
    }
    cout << str1 <<'n';
}