The challenge
Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
The solution in Java code
Option 1:
1
2
3
4
5
|
class Solution {
static String removeExclamationMarks(String s) {
return s.replaceAll("!", "");
}
}
|
Option 2:
1
2
3
4
5
|
class Solution {
static String removeExclamationMarks(String s) {
return s.replace("!", "");
}
}
|
Test cases to validate our solution in Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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("!", "");
}
}
|