How to Remove all Vowels from a String in Java

The challenge

Remove all vowels from the string.

Vowels:

a e i o u A E I O U

The solution in Java code

Option 1:

public class VowelRemoval { public static String disemvowel(String str) { return str.replaceAll("[aAeEiIoOuU]", ""); } }
Code language: Java (java)

Option 2:

public class VowelRemoval { public static String disemvowel(String str) { return str.replaceAll("(?i)[aeiou]" , ""); } }
Code language: Java (java)

Option 3:

public class VowelRemoval { public static String disemvowel(String str) { return str .replaceAll("a", "").replaceAll("A", "") .replaceAll("e", "").replaceAll("E", "") .replaceAll("i", "").replaceAll("I", "") .replaceAll("o", "").replaceAll("O", "") .replaceAll("u", "").replaceAll("U", ""); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.lang.StringBuilder; import java.util.Random; public class Tests { @Test public void FixedTests() { assertEquals("Ths wbst s fr lsrs LL!" , VowelRemoval.disemvowel("This website is for losers LOL!")); assertEquals("N ffns bt,\nYr wrtng s mng th wrst 'v vr rd", VowelRemoval.disemvowel ("No offense but,\nYour writing is among the worst I've ever read")); assertEquals("Wht r y, cmmnst?" , VowelRemoval.disemvowel("What are you, a communist?")); } public static String generateRandomChars(String candidateChars, int length) { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { sb.append(candidateChars.charAt(random.nextInt(candidateChars.length()))); } return sb.toString(); } public static String C(String Z) { return Z.replaceAll("(?i)[aeiou]" , ""); } @Test public void RandomTests() { for(int i = 0; i < 100; i++) { String X = generateRandomChars( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", i + 3); assertEquals(C(X) , VowelRemoval.disemvowel(X)); } } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments