c++ - 从字符串 C++ 中删除元音
问题描述
所以我是 C++ 的新手,并试图创建一个从字符串中删除元音的函数,但我失败了,这是我的代码到目前为止:
#include <string>
using namespace std;
string remove(string st) {
for(int i = 0; st[i] != '\0'; i++)
st[i] = st[i] == 'a' || st[i] == 'e' || st[i] == 'i' || st[i] == 'o' || st[i] ==
'u' || st[i] == 'A' || st[i] == 'E' || st[i] == 'I' || st[i] == 'O' || st[i] ==
'U' ? '' : st[i];
}
return st;
这似乎抛出一个错误?知道我做错了什么
我得到的错误是:
main.cpp:10:16: error: expected expression 'U' ? '' : Z[i];
并在另一个解释器上运行:
.code.tio.cpp:7:14: error: incompatible operand types ('const char *' and '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'char'))
'U' ? "" : Z[i];
^ ~~ ~~~~
解决方案
根据谓词(条件)从顺序容器中删除元素的规范方法是使用std::remove_if
. 不像它的名字所暗示的那样,这个标准算法并没有完全删除元素,它将它们移动到容器的后面,这样它们就很容易擦除,而其他元素则保持不变并保持相同的顺序。它返回一个迭代器,该迭代器指示包含“已删除”元素的容器部分的开始。由于标准算法无法更改它们操作的容器的大小,因此必须使用容器的适当删除方法删除这些元素。在 的情况下std::string
,就是std::string::erase
。
std::remove_if
接受一对定义要检查的元素范围的迭代器,以及一个用于确定要删除哪些元素的谓词。true
删除谓词的元素。
#include <algorithm>
#include <iostream>
#include <string>
// Returns true if p_char is a vowel
bool is_vowel(const char p_char)
{
constexpr char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
return std::find(std::begin(vowels), std::end(vowels), p_char) != std::end(vowels);
}
std::string remove_vowel(std::string st)
{
// Moves all the characters for which `is_vowel` is true to the back
// and returns an iterator to the first such character
auto to_erase = std::remove_if(st.begin(), st.end(), is_vowel);
// Actually remove the unwanted characters from the string
st.erase(to_erase, st.end());
return st;
}
int main()
{
std::cout << remove_vowel("Hello, World!");
}
推荐阅读
- android - 使用 FileProvider Android 从可移动 SD 卡打开文件时出错
- arrays - 如何将数组数据从请求保存到 Laravel 中的数据库?
- javascript - 我如何从 puppeteer 发送 get ?
- javascript - 用useEffect显示模态的方法是什么?
- python - 如何使用 python 或 pandas 根据包含字典列表的列过滤 DataFrame?
- amazon-web-services - 通过 event.get() 调用 Lambda 事件?
- java - 如何使用 void set 方法在静态常量助手类中创建对象?
- json - 创建 json 的哈希/指纹 - 最佳(快速)方式
- vagrant - vagrant & virtualbox:两个仅主机的网络接口不允许重叠
- export-to-csv - 在 dbVisualizer 中设置 CSV 输出的小数点分隔符