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

Muh*_*man 0 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;
Run Code Online (Sandbox Code Playgroud)

这似乎引发了一个错误?我知道我做错了什么

我得到的错误是:

main.cpp:10:16: error: expected expression 'U' ? '' : Z[i];
Run Code Online (Sandbox Code Playgroud)

并在另一个解释器上运行:

   .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];
                ^ ~~   ~~~~
Run Code Online (Sandbox Code Playgroud)

Fra*_*eux 6

根据谓词(条件)从顺序容器中删除元素的规范方法是使用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!");
}
Run Code Online (Sandbox Code Playgroud)