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

Remove vowels from string C++

所以我是 C++ 的新手,并试图创建一个函数来从字符串中删除元音,但我非常失败,这是我目前的代码:

#include <string>
using namespace std;
string remove(string st) {
    for(int i = 0; st[i] != '[=10=]'; 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];
                ^ ~~   ~~~~

'' 不是有效字符,您不能将 "empty" 字符(C++ 中不存在这样的字符)放入字符串中以删除内容...

你可以做的是移动非元音字母,i。 e.辅音,到前面,跳过元音,然后擦掉末尾多余的字符:

auto pos = st.begin();
for(auto c : st)
{
    if(isConsonant(c))
        *pos++ = c;
}
st.erase(pos, st.end());

编辑:正如 François(正确地)指出的那样:无需重新发明轮子(前提是您未被禁止使用标准库):

st.erase(std::remove_if(st.begin(), st.end(), [](char c) { return isConsonant(c); }), st.end());

请注意,std::remove_if(以及 std::remove)"remove" 只需将元素移动到保留在前面,并将迭代器 returns 移动到新的末尾数据——但并没有真正删除元素 "behind" 新的结束。所以有必要明确地 erase 它们,如上所示。

根据谓词(条件)从顺序容器中删除元素的规范方法是使用 std::remove_if. Unlike it's name implies, this standard algorithm doesn't quite remove the elements, it moves them to the back of the container so they are easy to erase, leaving the other elements intact and in the same order. It returns an iterator that indicates the beginning of the portion of the container which contains the "removed" elements. Since the standard algorithms cannot change the size the containers they operate on, these elements must then be removed using the container's appropriate remove method. In the case of std::string, that's 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!");
}