(New String split method) The split method in the String class returns an array of strings consisting of the substrings split by the delimiters. However, the delimiters are not returned. Implement the following new method that returns an array of strings consisting the substrings split by the matching delimiters, including the matching delimiters. public static String[] split(String s, String regex) For example, split(“ab#12#453”, “#”) returns ab,#,12,#,453 in an array of String, and split(“a?b?gf#e”,”[?#]”) returns a, ?, b, ?, gf, #, and e in an array of String.用arraylist写java代码
时间: 2024-03-07 12:47:21 浏览: 60
java的String[] split 示例
3星 · 编辑精心推荐
这里是使用 ArrayList 实现的 Java 代码:
```java
import java.util.ArrayList;
public class StringSplitter {
public static String[] split(String s, String regex) {
ArrayList<String> result = new ArrayList<String>();
int start = 0, end;
while ((end = s.indexOf(regex, start)) != -1) {
result.add(s.substring(start, end + regex.length()));
start = end + regex.length();
}
result.add(s.substring(start));
return result.toArray(new String[result.size()]);
}
public static void main(String[] args) {
String s1 = "ab#12#453";
String[] result1 = split(s1, "#");
for (String str : result1) {
System.out.print(str + ",");
}
System.out.println();
String s2 = "a?b?gf#e";
String[] result2 = split(s2, "[?#]");
for (String str : result2) {
System.out.print(str + ",");
}
System.out.println();
}
}
```
输出结果为:
```
ab,#,12,#,453,
a,?,b,?,gf,#,e,
```
阅读全文