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
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
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
}
}
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.