在日常开发中,经常会用到字符串分割,一般使用split方法,但是这种简单的方法不能保留分割符号,于是自己动手造轮子,记录一个字符传分割方法,适配单个字符分割,多个字符分割,均可保留分割符。
具体实现代码如下:
public static void main(String[] args) {
final String[] aEach = splitSentence("[(WD1){D5}][(h7m0){h3}][(WD1){D5}]", "\\]\\[");
System.out.println(aEach.length);
final String[] aEach1 = splitSentence("[(WD1){D5}][(h7m0){h3}][(WD1){D5}]", "\\{");
System.out.println(aEach1.length);
final String[] aEach2 = splitSentence("[(WD1){D5}][(h7m0){h3}][(WD1){D5}]", "\\]\\[\\(");
System.out.println(aEach2.length);
}
/**
* 通过分隔符拆分句子,并保留分隔符
*
* @return
*/
public static String[] splitSentence(String sentence, String chars) {
//1. 定义匹配模式
Pattern p = Pattern.compile(chars);
Matcher m = p.matcher(sentence);
//2. 拆分句子[拆分后的句子符号也没了]
String[] words = p.split(sentence);
String afterChars = chars.replace("\\", "");
//3. 保留原来的分隔符
if (afterChars.length() != 2) {
if (words.length > 0) {
int count = 0;
while (count < words.length) {
if (m.find()) {
words[count] += m.group();
}
count++;
}
}
} else {
//chars.length() ==2
if (words.length > 1) {
int count = 0;
String splitStr1 = afterChars.substring(0, 1);
String splitStr2 = afterChars.substring(1, 2);
while (count < words.length) {
if (count == 0) {
words[count] += splitStr1;
} else if (count == words.length - 1) {
words[count] = splitStr2 + words[count];
} else {
words[count] = splitStr2 + words[count] + splitStr1;
}
count++;
}
}
}
return words;
}
运行结果:
- 分隔符为2个字符
aEach:以双分隔符"]["切分:结果:[(WD1){D5}] 、 [(h7m0){h3}] 、 [(WD1){D5}]
- 分割符为单个字符
aEach1:以双分隔符"}"切分:结果:[(WD1){D5} 、 ][(h7m0){h3} 、 ][(WD1){D5} 、]
- 风格符为3个字符
aEach2:以双分隔符"][}"切分:结果:[(WD1){D5}][( 、 h7m0){h3}][( 、 WD1){D5}]
---------------------------------------------------------------------------------------------------------------------------------
幸福的人生,需要三种姿态:对过去,要淡;对现在,要惜;对未来,要信。