forked from RameshMF/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.java
More file actions
71 lines (53 loc) · 1.88 KB
/
Copy pathStrings.java
File metadata and controls
71 lines (53 loc) · 1.88 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package modern.challenge;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class Strings {
private Strings() {
throw new AssertionError("Cannot be instantiated");
}
public static String removeCharacterV1(String str, char ch) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return "";
}
StringBuilder sb = new StringBuilder();
char[] chArray = str.toCharArray();
for (char c : chArray) {
if (c != ch) {
sb.append(c);
}
}
return sb.toString();
}
public static String removeCharacterV2(String str, char ch) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return "";
}
return str.replaceAll(Pattern.quote(String.valueOf(ch)), "");
}
public static String removeCharacterV3(String str, char ch) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return "";
}
return str.chars()
.filter(c -> c != ch)
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
}
public static String removeCharacterV4(String str, String ch) {
if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
// or throw IllegalArgumentException
return "";
}
if (ch.codePointCount(0, ch.length()) != 1) {
return ""; // there is more than 1 Unicode character in the given String
}
int codePoint = ch.codePointAt(0);
return str.codePoints()
.filter(c -> c != codePoint)
.mapToObj(c -> String.valueOf(Character.toChars(c)))
.collect(Collectors.joining());
}
}