How to Remove all Exclamation Marks from a String in Java

The challenge

Write function RemoveExclamationMarks which removes all exclamation marks from a given string.

The solution in Java code

Option 1:

class Solution { static String removeExclamationMarks(String s) { return s.replaceAll("!", ""); } }
Code language: Java (java)

Option 2:

class Solution { static String removeExclamationMarks(String s) { return s.replace("!", ""); } }
Code language: Java (java)

Test cases to validate our solution in Java

import org.junit.Test; import java.util.Random; import java.util.stream.*; import static org.junit.Assert.assertEquals; public class SolutionTest { @Test public void testSimpleString1() { assertEquals("Hello World", Solution.removeExclamationMarks("Hello World!")); } @Test public void testSimpleString2() { assertEquals("Hello World", Solution.removeExclamationMarks("Hello World!!!")); } @Test public void testSimpleString3() { assertEquals("Hi Hello", Solution.removeExclamationMarks("Hi! Hello!")); } @Test public void testRandomString() { String rs = String.format("%s!%s %s!%s", randomString(), randomString(), randomString(), randomString()); assertEquals(solution(rs), Solution.removeExclamationMarks(rs)); } private String randomString() { Random random = new Random(); String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZbcdefghijklmnopqrstuvwxyz"; return IntStream.range(0, 10) .mapToObj(__ -> (char) abc.charAt(random.nextInt(abc.length()))) .map(String::valueOf) .collect(Collectors.joining("")); } private String solution(String s) { return s.replaceAll("!", ""); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments