Hello I'm trying to add the String OB before every vowel(A,E,I,O,U) in my text. I can assume that the text is made up of all capital letters, no spaces or punctuation. These are handled by other methods I was able to create.
This is what I have so far:
public static String obify(String s){
String text = s;
String[] capVowels = {"A", "E", "I", "O", "U"};
for (String vow : capVowels){
text = text.replace(vow, "OB" + vow);
}
return text;
}
but when I pass it a sting it prints two OB before the first vowel. Example input: HELLOWOLD , output: HOBOBELLOBOWOBOLD
Any help would be appreciated with an explanation.
You can use a regular expression character class to replace all the vowels with "OB{vowel}" via String#replaceAll
. For example
final String test = s.replaceAll("[AEIOU]", "OB$0");
The $0
represents the matched string, ie the vowel.
The reason you're getting duplicate "OB" strings in the result is because of your for-loop. The problem is you add more vowels with each iteration, ie the "O" in "OB", so when you get up to your "O" iteration, it's replacing the ones you added.