c++ - 从字符串 C++ 中删除元音

标签 c++ regex string str-replace

所以我是 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!");
}

关于c++ - 从字符串 C++ 中删除元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50845519/

相关文章:

regex - 检查字符串是否包含 1 个数字、1 个字母且长度在 5-15 个字符之间

python - 条件正则表达式

c++ - boost 正则表达式格式化程序,如何使用自定义函数

iphone - iOS访问字符串中的字符

Python:字符串连接类型错误 - 一元 + 的错误操作数类型: 'str'

php - 在php中清理句子

c++ - 双线性插值,我的实现有问题

c++ - 将 boost 图拆分为连接的组件

C++ : How to programmatically define template types in runtime?

c++ - Opengl 通过使用顶点缓冲对象