Skip to content

Commit 3dde024

Browse files
authored
Add files via upload
1 parent 2292e4e commit 3dde024

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package ch_10;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
6+
/**
7+
* **10.25 (New string split method) The split method in the String class returns an
8+
* array of strings consisting of the substrings split by the delimiters. However, the
9+
* delimiters are not returned. Implement the following new method that returns
10+
* an array of strings consisting of the substrings split by the matching delimiters,
11+
* including the matching delimiters.
12+
* <p>
13+
* public static String[] split(String s, String regex)
14+
* For example, split("ab#12#453", "#") returns ab, #, 12, #, 453 in an
15+
* array of String, and split("a?b?gf#e", "[?#]") returns a, b, ?, b, gf,
16+
* #, and e in an array of String.
17+
*/
18+
public class Exercise10_25 {
19+
20+
public static void main(String[] args) {
21+
/* Tests */
22+
String s = "ab#12#453";
23+
String regex = "#";
24+
String s2 = "a?b?gf#e";
25+
String regex2 = "[?#]";
26+
27+
System.out.println("split(\"ab#12#453\",\"#\"): " + Arrays.toString(split(s, regex)));
28+
System.out.println("split(\"a?b?gf#e\",\"[?#]\"): " + Arrays.toString(split(s2, regex2)));
29+
}
30+
31+
public static String[] split(String s, String regex) {
32+
ArrayList<String> splitList = new ArrayList<>();
33+
if (regex == null || regex.length() < 1) {
34+
return new String[]{"regex must not be null and length must be greater than 0"};
35+
}
36+
37+
ArrayList<Character> splitters = new ArrayList<>();
38+
for (char ch : regex.toCharArray()) {
39+
if (ch == '[' || ch == ']') continue;
40+
splitters.add(ch);
41+
}
42+
String subString = "";
43+
for (int i = 0; i < s.length(); i++) {
44+
if (splitters.contains(s.charAt(i))) {
45+
if (subString.length() > 0) {
46+
splitList.add(subString);
47+
subString = "";
48+
}
49+
50+
splitList.add(s.charAt(i) + "");
51+
i++;
52+
while (i < s.length()) {
53+
if (!splitters.contains(s.charAt(i))) {
54+
subString = subString.concat(s.charAt(i) + "");
55+
} else {
56+
splitList.add(subString);
57+
subString = "";
58+
splitList.add(s.charAt(i) + "");
59+
break;
60+
}
61+
i++;
62+
}
63+
} else {
64+
subString = subString.concat(s.charAt(i) + "");
65+
}
66+
}
67+
if (subString.length() > 0) {
68+
splitList.add(subString);
69+
}
70+
return splitList.toArray(new String[]{});
71+
72+
}
73+
}

0 commit comments

Comments
 (0)