mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
添加 Windows 资源管理器风格字符串比较器
This commit is contained in:
parent
bd164db9b4
commit
8bb736b375
@ -12,6 +12,7 @@
|
||||
* 【csv 】 CsvWriter.writeBeans增加重载,可选是否写出表头(issue#IA57W2@Gitee)
|
||||
* 【core 】 BetweenFormatter支持自定义设置单位(pr#1228@Gitee)
|
||||
* 【cache 】 Cache.put变更策略,对于替换的键值对,不清理队列(issue#3618@Github)
|
||||
* 【core 】 添加 Windows 资源管理器风格字符串比较器(pr#3620@Github)
|
||||
|
||||
### 🐞Bug修复
|
||||
* 【core 】 修复AnnotationUtil可能的空指针错误
|
||||
|
@ -1,5 +1,7 @@
|
||||
package cn.hutool.core.comparator;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
@ -19,15 +21,19 @@ import java.util.regex.Pattern;
|
||||
* "abc12.doc" }},这与在资源管理器中看到的相同</p>
|
||||
*
|
||||
* @author YMNNs
|
||||
* @see
|
||||
* <a href="https://stackoverflow.com/questions/23205020/java-sort-strings-like-windows-explorer">Java - Sort Strings like Windows Explorer</a>
|
||||
* @see <a href="https://stackoverflow.com/questions/23205020/java-sort-strings-like-windows-explorer">Java - Sort Strings like Windows Explorer</a>
|
||||
*/
|
||||
public class WindowsExplorerStringComparator implements Comparator<String> {
|
||||
public class WindowsExplorerStringComparator implements Comparator<CharSequence> {
|
||||
|
||||
/**
|
||||
* 单例
|
||||
*/
|
||||
public static final WindowsExplorerStringComparator INSTANCE = new WindowsExplorerStringComparator();
|
||||
|
||||
private static final Pattern splitPattern = Pattern.compile("\\d+|\\.|\\s");
|
||||
|
||||
@Override
|
||||
public int compare(String str1, String str2) {
|
||||
public int compare(CharSequence str1, CharSequence str2) {
|
||||
Iterator<String> i1 = splitStringPreserveDelimiter(str1).iterator();
|
||||
Iterator<String> i2 = splitStringPreserveDelimiter(str2).iterator();
|
||||
while (true) {
|
||||
@ -65,16 +71,16 @@ public class WindowsExplorerStringComparator implements Comparator<String> {
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> splitStringPreserveDelimiter(String str) {
|
||||
private List<String> splitStringPreserveDelimiter(CharSequence str) {
|
||||
Matcher matcher = splitPattern.matcher(str);
|
||||
List<String> list = new ArrayList<>();
|
||||
int pos = 0;
|
||||
while (matcher.find()) {
|
||||
list.add(str.substring(pos, matcher.start()));
|
||||
list.add(StrUtil.sub(str, pos, matcher.start()));
|
||||
list.add(matcher.group());
|
||||
pos = matcher.end();
|
||||
}
|
||||
list.add(str.substring(pos));
|
||||
list.add(StrUtil.subSuf(str, pos));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ import java.util.List;
|
||||
*
|
||||
* @author YMNNs
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class WindowsExplorerStringComparatorTest {
|
||||
|
||||
List<String> answer1 = new ArrayList<String>() {{
|
||||
|
Loading…
x
Reference in New Issue
Block a user