从字符串"Hello, have a good day"中删除所有辅音
delete all consonents from the string "Hello, have a good day"
我已经看到很多很好的代码来解决这个问题。我是编码新手。我的问题是我的逻辑哪里出了问题。 我认为问题出在第二个字符串 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';
}
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- C++中的线程安全删除
- 如何从存储在std::映射中的std::集中删除元素
- 从字符串"Hello, have a good day"中删除所有辅音