废话不多说,直接撸代码:
/**
* @Describe: 手写字符串分割
**/
public class Test {
public static void main(String[] args) {
String str = "ab,#cd,#e";
String split = ",#";
System.out.println(split(str, split));
String regex = "[^(,#)]+";
System.out.println(splitByRegex(str, regex));
}
/*
* @describe: 实现按指定字符进行字符串分割
* @param str
* @param split
* @return: java.util.List<java.lang.String>
*/
public static List<String> split(String str, String split) {
List<String> result = new ArrayList<>();
int start = 0;
while(start < str.length() - 1) {
int in = str.indexOf(split, start);
if (in == -1) {
result.add(str.substring(start));
break;
}
if (in > 0) {
result.add(str.substring(start, in));
}
start = in + split.length();
}
return result;
}
/*
* @describe: 实现按正则表达式实现字符串分割
* @param str
* @param regex
* @return: java.util.List<java.lang.String>
*/
public static List<String> splitByRegex(String str, String regex) {
List<String> result = new ArrayList<>();
Pattern compile = Pattern.compile(regex);
Matcher matcher = compile.matcher(str);
while (matcher.find()) { // 往后逐个匹配
result.add(matcher.group());
}
return result;
}
}
输出结果:
[ab, cd, e]
[ab, cd, e]
说明:
正则表达式进行字符串分割,该方法入参【regex】也可以传入正常的分割字符串,如:“,#”,然后组装成正则表达式:"[^("+regex+")]+"即可。