有这样的需求,需要合并消息,本来打算自定义mysql函数来实现这功能,但感觉比较繁琐,最后改用代码实现。
最终要实现的效果为:例如6号窗口,7号窗口,10号窗口,11号窗口 变为 6-7号窗口,10-11号窗口
最后果断上代码:
package com.expo.testDemo;
import cn.hutool.core.util.StrUtil;
import java.util.Arrays;
public class Ceshi {
public static void main(String[] args) {
String text="31号窗口,30号窗口,32号窗口,33号窗口,34号窗口,35号窗口,36号窗口,37号窗口,46号窗口,47号窗口,48号窗口,49号窗口,50号窗口,51号窗口,52号窗口,53号窗口,54号窗口,55号窗口,56号窗口,57号窗口,58号窗口";
String text1="税务预审窗口";
if(StrUtil.contains(text,',')){
String dd=StrUtil.replace(text,"号窗口","");
String[] ss= StrUtil.split(dd,",");
int[] array = Arrays.asList(ss).stream().mapToInt(Integer::parseInt).toArray();
Arrays.sort(array);
String result = convert(array, 0);
System.out.println(StrUtil.sub(result,0,result.length()-1));
}else{
System.out.println("你毛都没有");
}
}
public static String convert(int[] ints, int index) {
int end = index;
if (ints.length == index) {
return "";
} else {
for (int i = index; i < ints.length; i++) {
if (i < ints.length - 1) {
if (ints[i] + 1 == ints[i + 1]) {
end = i;
} else {
if (i > index)
end = end + 1;
break;
}
} else {
if (end == ints.length - 2) {
end = ints.length - 1;
break;
}
}
}
if (index == end) //相等说明不连续
return ints[index] + "号窗口," + convert(ints, end + 1);
else{
return ints[index] + "-" + ints[end] + "号窗口," + convert(ints, end + 1);
}
}
}
}