How to Replace all Vowels in a String in Java

0 min read 180 words

The challenge

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

Examples

replace("Hi!") === "H!!"
replace("!Hi! Hi!") === "!H!! H!!"
replace("aeiou") === "!!!!!"
replace("ABCDE") === "!BCD!"

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=0; 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();
    }
}

A more efficient method using replaceAll:

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

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("!");
    }
}

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"));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags