Matthew Carlson Matthew Carlson - 22 days ago 6
Java Question

Attempting to remove characters from a string

I am attempting to remove vowels from a randomly generated 20 letter word. I have to use substring for this assignment but am having issues with it conceptually. With this code, the value of word never changes and stays its original value. When I do i+2 for the second half of the string it jumps two characters and messes up when there are two vowels directly after one another. If I have to use substring how can I improve this to work every time.

public class WordsWithoutVowels {
String finalWord;

public WordsWithoutVowels(String word) {
for(int i = 0; i < 20; i++) {
if(word.charAt(i) == 'a') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'e') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'i') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'o') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'u') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'y') {word = word.substring(0, i) + word.substring(i++);}
System.out.println(word);
}
finalWord = word;
}

public String getWord()
{
return finalWord;
}
}

Answer

You can use the simplified code as below to do so:

public static void main(String[] args) {
        String stringPara = "this example will remove the vowals aeiou";
        stringPara = removeCharFromString(stringPara, "a");
        stringPara = removeCharFromString(stringPara, "e");
        stringPara = removeCharFromString(stringPara, "i");
        stringPara = removeCharFromString(stringPara, "o");
        stringPara = removeCharFromString(stringPara, "u");
        System.out.println(stringPara);
    }

    public static String removeCharFromString(String str, String characterToRemove){
        while(str.contains(characterToRemove)){
            str = str.substring(0, str.indexOf(characterToRemove)) + str.substring(str.indexOf(characterToRemove)+1, str.length()) ;
        }
        return str;
    }