Why is the code is not removing “u” from the input string?

前端 未结 3 843
礼貌的吻别
礼貌的吻别 2021-01-19 16:22

I am learning C++. Today I have written a code to remove vowels form a string. It works fine in some tests. But this test is failing to remove "u" from a string. M

3条回答
  •  佛祖请我去吃肉
    2021-01-19 17:20

    When you erase a character, your index i is still being incremented, which means you are skipping checking characters that appear right after a vowel.

    You need to decrement i when you erase a character:

    if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u')
    {
        word.erase(word.begin() + i);  // Removing specific character
        --i;  // make sure to check the next character
    }
    

    Here's a demo.

    Also, please avoid the following 2 lines:

    #include 
    using namespace std;
    

    They are dangerous and should not be used.

提交回复
热议问题