Replacing all vowels in string with String.join() and split() methods

Viewed 105

I need to replace every vowels in a given string with the same vowel, followed by the letter "v", followed by the vowel a second time. As an example: bad should become bavad, egg becomes evegg, doge becomes dovogeve, etc. The exercise explicitly states that it needs to be done with String.join() method. So far, I've come up with this.

String string = "bad";
int length = string.length();
for (int i = 0; i < length; i++) {
    char c = string.charAt(i);
    if (isVowel(c)) {
        string = String.join(c + "v" + c, string.split("" + c));
        length += 2;
        i += 2;
    }
}
System.out.println(string);

The following isVowel method is a simple method to check whether a given char is a vowel or not

public static boolean isVowel(char c) {
    return Arrays.asList('a', 'u', 'o', 'e', 'i').contains(c);
}

This solution is working fine for strings like bad, sad, step, etc. However, if I try it with aeiou, the output is avaeveiviovo instead of avaeveiviovouvu.

3 Answers

Here is one way.

String[] data = {"bad", "happy", "computer", "java", "vacuum"};
for (String word : data) {
     System.out.printf("%-10s --> %s%n",word,modVowels(word));
}

prints

bad        --> bavad
happy      --> havappy
computer   --> covompuvutever
java       --> javavava
vacuum     --> vavacuvuuvum
  • initialize newString to an empty string
  • then split the word into individual strings of one character.
  • if the character is a vowel, append the modified string.
  • else just append the character.
  • then return the result.
public static String modVowels(String word) {
    String[] chars = word.split("");
    String newString = "";
    for (int i = 0; i < chars.length; i++) {
        String ch = chars[i];
        if ("aeiou".contains(ch)) {
            ch = ch+"v"+ch;
        }
        newString = String.join("",newString, ch);
    }
    return newString;
}

You could use a String to store the result

String string = "aeiou";
int length = string.length();
String result = "";

for (int i=0; i<length; i++) {
    char c = string.charAt(i);

    if(isVowel(c)) 
       result += String.join(result, c+"v"+c);
    else
       result += c;
}

System.out.println(result);   //Output "avaeveiviovouvu"

As mentioned by others in the comments, your code has many other issues and edge cases apart from what you've noticed. But I'll be answering just your original question. u is not joined because of how String.split() behaves (emphasis mine):

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

So while a splits to be ["", "eiou"], u becomes [avaeveiviovo] and there is no empty string to join with.

Related