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

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

    Here's how you can do it more easily:

    #include <algorithm>
    #include <array>
    #include <cctype>
    #include <iostream>
    #include <string>
    
    constexpr auto isVowel(unsigned char const ch) noexcept {
      constexpr std::array<unsigned char, 10> vowels{
          'a', 'e', 'i', 'o', 'u',
      };
      return std::find(vowels.begin(), vowels.end(), std::tolower(ch)) !=
             vowels.end();
    }
    
    int main() {
      std::string str = "Tour";
      str.erase(std::remove_if(str.begin(), str.end(), isVowel), str.end());
      std::cout << str << '\n';
    }
    

    Try online

    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
  • 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 <bits/stdc++.h>
    using namespace std;
    

    They are dangerous and should not be used.

    0 讨论(0)
提交回复
热议问题