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

前端 未结 3 833
礼貌的吻别
礼貌的吻别 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:07

    After erase, i++ is performed. That means one element is bypassed by the check.

    Change the for loop to

    for (int i = 0; i < word.length(); )
    {
        if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u')
        {
            word.erase(word.begin() + i);  // Removing specific character
        } 
        else 
        {
            i++; // increment when no erasion is performed
        }
    }
    

提交回复
热议问题