forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStrings.java
More file actions
103 lines (77 loc) · 2.93 KB
/
Copy pathStrings.java
File metadata and controls
103 lines (77 loc) · 2.93 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package modern.challenge;
public final class Strings {
private Strings() {
throw new AssertionError("Cannot be instantiated");
}
public static int countOccurrencesOfACertainCharacterV1(String str, char ch) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return -1;
}
return str.length() - str.replace(String.valueOf(ch), "").length();
}
public static int countOccurrencesOfACertainCharacterVCP1(String str, String ch) {
if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
// or throw IllegalArgumentException
return -1;
}
if (ch.codePointCount(0, ch.length()) > 1) {
return -1; // there is more than 1 Unicode character in the given String
}
int result = str.length() - str.replace(ch, "").length();
// if ch.length() return 2 then this is a Unicode surrogate pair
return ch.length() == 2 ? result / 2 : result;
}
public static int countOccurrencesOfACertainCharacterV2(String str, char ch) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return -1;
}
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
return count;
}
public static int countOccurrencesOfACertainCharacterVCP2(String str, String ch) {
if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
// or throw IllegalArgumentException
return -1;
}
if (ch.codePointCount(0, ch.length()) > 1) {
return -1; // there is more than 1 Unicode character in the given String
}
int count = 0;
int codePoint = ch.codePointAt(0);
for (int i = 0; i < str.length(); i++) {
if (str.codePointAt(i) == codePoint) {
count++;
}
}
return count;
}
public static long countOccurrencesOfACertainCharacterV3(String str, char ch) {
if (str == null || str.isEmpty()) {
// or throw IllegalArgumentException
return -1;
}
return str.chars()
.filter(c -> c == ch)
.count();
}
public static long countOccurrencesOfACertainCharacterVCP3(String str, String ch) {
if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
// or throw IllegalArgumentException
return -1;
}
if (ch.codePointCount(0, ch.length()) > 1) {
return -1; // there is more than 1 Unicode character in the given String
}
int codePoint = ch.codePointAt(0);
return str.codePoints()
.filter(c -> c == codePoint)
.count();
}
}