forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.java
More file actions
69 lines (50 loc) · 1.74 KB
/
Strings.java
File metadata and controls
69 lines (50 loc) · 1.74 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
package modern.challenge;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Strings {
private Strings() {
throw new AssertionError("Cannot be instantiated");
}
public static int countStringInStringV1(String string, String toFind) {
if (string == null || toFind == null) {
throw new IllegalArgumentException("The given strings cannot be null");
}
if (string.isBlank() || toFind.isBlank()) {
return 0;
}
int position = 0;
int count = 0;
int n = toFind.length();
while ((position = string.indexOf(toFind, position)) != -1) {
position = position + n;
count++;
}
return count;
}
public static int countStringInStringV2(String string, String toFind) {
if (string == null || toFind == null) {
throw new IllegalArgumentException("The given strings cannot be null");
}
if (string.isBlank() || toFind.isBlank()) {
return 0;
}
return string.split(Pattern.quote(toFind), -1).length - 1;
}
public static int countStringInStringV3(String string, String toFind) {
if (string == null || toFind == null) {
throw new IllegalArgumentException("The given strings cannot be null");
}
if (string.isBlank() || toFind.isBlank()) {
return 0;
}
Pattern pattern = Pattern.compile(Pattern.quote(toFind));
Matcher matcher = pattern.matcher(string);
int position = 0;
int count = 0;
while (matcher.find(position)) {
position = matcher.start() + 1;
count++;
}
return count;
}
}