Skip to content

How to Replace all Vowels in a String in Java

The challenge

Replace all vowel to exclamation mark in the sentence. aeiouAEIOU is vowel.


replace("Hi!") === "H!!" replace("!Hi! Hi!") === "!H!! H!!" replace("aeiou") === "!!!!!" replace("ABCDE") === "!BCD!"
Code language: JavaScript (javascript)

The solution in Java code

We could use a StringBuilder and a switch case as a first attempt:

public class Solution { public static String replace(final String s) { StringBuilder sb = new StringBuilder(); for (int i=; i<s.length(); i++) { switch(Character.toLowerCase(s.charAt(i))) { case 'a': case 'e': case 'i': case 'o': case 'u': sb.append("!"); break; default: sb.append(s.charAt(i)); break; } } return sb.toString(); } }
Code language: Java (java)

A more efficient method using replaceAll:

public class Solution { public static String replace(final String s) { return s.replaceAll("[aeiouAEIOU]", "!"); } }
Code language: Java (java)

How to use the regex replacer:

import java.util.regex.*; public class Solution { private static Pattern vowels = Pattern.compile("[aeiou]", Pattern.CASE_INSENSITIVE); public static String replace(final String s) { return vowels.matcher(s).replaceAll("!"); } }
Code language: Java (java)

Test cases to validate our Java code solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SampleTest { @Test public void basicTests() { assertEquals("H!!", Solution.replace("Hi!")); assertEquals("!H!! H!!", Solution.replace("!Hi! Hi!")); assertEquals("!!!!!", Solution.replace("aeiou")); assertEquals("!BCD!", Solution.replace("ABCDE")); } }
Code language: Java (java)

See also  How to Subtract Arrays in Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x