含字母数字的字符串排序算法,仿Windows文件名排序算法
不废话,上排序前后对比:
类似与windows的目录文件排序,分几种版本C++/C#/JAVA给大家:
1、Java版
package com.eam.util;
/*
* The Alphanum Algorithm is an improved sorting algorithm for strings
* containing numbers. Instead of sorting numbers in ASCII order like
* a standard sort, this algorithm sorts numbers in numeric order.
*
* The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
*
* Released under the MIT License - https://opensource.org/licenses/MIT
*
* Copyright 2007-2017 David Koelle
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors; /**
* This is an updated version with enhancements made by Daniel Migowski,
* Andre Bogus, and David Koelle. Updated by David Koelle in 2017.
*
* To use this class:
* Use the static "sort" method from the java.util.Collections class:
* Collections.sort(your list, new AlphanumComparator());
*/
public class AlphanumComparator implements Comparator<String>
{
private final boolean isDigit(char ch)
{
return ((ch >= 48) && (ch <= 57));
} /** Length of string is passed in for improved efficiency (only need to calculate it once) **/
private final String getChunk(String s, int slength, int marker)
{
StringBuilder chunk = new StringBuilder();
char c = s.charAt(marker);
chunk.append(c);
marker++;
if (isDigit(c))
{
while (marker < slength)
{
c = s.charAt(marker);
if (!isDigit(c)) {
break;
}
chunk.append(c);
marker++;
}
} else
{
while (marker < slength)
{
c = s.charAt(marker);
if (isDigit(c)) {
break;
}
chunk.append(c);
marker++;
}
}
return chunk.toString();
} @Override
public int compare(String s1, String s2)
{
if ((s1 == null) || (s2 == null))
{
return 0;
} int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
}
else
{
result = thisChunk.compareTo(thatChunk);
} if (result != 0) {
return result;
}
} return s1Length - s2Length;
} /**
* Shows an example of how the comparator works.
* Feel free to delete this in your own code!
*/
public static void main(String[] args) {
List<String> values = Arrays.asList("ASH_1", "ASH_11", "ASH_12", "ASH_100", "HJ1", "HJ_2", "HJ_10", "HJ_100", "1#定型机", "2#定型机", "10#定型机","染色机01#", "染色机02#", "染色机10#");
System.out.println(values.stream().sorted(new AlphanumComparator()).collect(Collectors.joining(" ")));
}
}
2、C#版
/*
* The Alphanum Algorithm is an improved sorting algorithm for strings
* containing numbers. Instead of sorting numbers in ASCII order like
* a standard sort, this algorithm sorts numbers in numeric order.
*
* The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
*
* Based on the Java implementation of Dave Koelle's Alphanum algorithm.
* Contributed by Jonathan Ruckwood <jonathan.ruckwood@gmail.com>
*
* Adapted by Dominik Hurnaus <dominik.hurnaus@gmail.com> to
* - correctly sort words where one word starts with another word
* - have slightly better performance
*
* Released under the MIT License - https://opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Collections;
using System.Text; /*
* Please compare against the latest Java version at http://www.DaveKoelle.com
* to see the most recent modifications
*/
namespace AlphanumComparator
{
public class AlphanumComparator : IComparer
{
private enum ChunkType {Alphanumeric, Numeric};
private bool InChunk(char ch, char otherCh)
{
ChunkType type = ChunkType.Alphanumeric; if (char.IsDigit(otherCh))
{
type = ChunkType.Numeric;
} if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
|| (type == ChunkType.Numeric && !char.IsDigit(ch)))
{
return false;
} return true;
} public int Compare(object x, object y)
{
String s1 = x as string;
String s2 = y as string;
if (s1 == null || s2 == null)
{
return 0;
} int thisMarker = 0, thisNumericChunk = 0;
int thatMarker = 0, thatNumericChunk = 0; while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
{
if (thisMarker >= s1.Length)
{
return -1;
}
else if (thatMarker >= s2.Length)
{
return 1;
}
char thisCh = s1[thisMarker];
char thatCh = s2[thatMarker]; StringBuilder thisChunk = new StringBuilder();
StringBuilder thatChunk = new StringBuilder(); while ((thisMarker < s1.Length) && (thisChunk.Length==0 ||InChunk(thisCh, thisChunk[0])))
{
thisChunk.Append(thisCh);
thisMarker++; if (thisMarker < s1.Length)
{
thisCh = s1[thisMarker];
}
} while ((thatMarker < s2.Length) && (thatChunk.Length==0 ||InChunk(thatCh, thatChunk[0])))
{
thatChunk.Append(thatCh);
thatMarker++; if (thatMarker < s2.Length)
{
thatCh = s2[thatMarker];
}
} int result = 0;
// If both chunks contain numeric characters, sort them numerically
if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
{
thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
thatNumericChunk = Convert.ToInt32(thatChunk.ToString()); if (thisNumericChunk < thatNumericChunk)
{
result = -1;
} if (thisNumericChunk > thatNumericChunk)
{
result = 1;
}
}
else
{
result = thisChunk.ToString().CompareTo(thatChunk.ToString());
} if (result != 0)
{
return result;
}
} return 0;
}
}
}
排序后:
含字母数字的字符串排序算法,仿Windows文件名排序算法的更多相关文章
- table中td 内容超长 自动折行 (含字母数字文字)
<table style="width:100%;table-layout:fixed;"> //列宽由表格宽度和列宽度设定 <thead> <th& ...
- 浅谈无字母数字构造webshell
0x00 问题 <?php include 'flag.php'; if(isset($_GET['code'])){ $code = $_GET['code']; if(strlen($cod ...
- C++(五十一) — 容器中常见算法(查找、排序、拷贝替换)
1.find(); find()算法的作用是在指定的一段序列中查找某个数,包含三个参数,前两个参数是表示元素范围的迭代器,第三个参数是要查找的值. 例:fing(vec.begin(), vec.en ...
- JS实现点击表头表格自动排序(含数字、字符串、日期)
这篇文章主要介绍了利用JS如何实现点击表头后表格自动排序,其中包含数字排序.字符串排序以及日期格式的排序,文中给出了完整的示例代码,并做了注释,相信大家都能看懂,感兴趣的朋友们一起来看看吧. < ...
- 用哈希算法的思想解决排序和字符串去重问题,时间复杂度为O(N)
第一个题目: int a[] = {12,13,12,13,19,18,15,12,15,16,17},要求对数组a进行排序,要求时间复杂度为O(N) 我们所知道的常规排序中,最优的解法也就是O(N* ...
- 如何使用PHP排序key为字母+数字的数组
你还在为如何使用PHP排序字母+数字的数组而烦恼吗? 今天有个小伙伴在群里问: 如何将一个key为字母+数字的数组按升序排序呢? 举个例子: $test = [ 'n1' => 22423, ' ...
- C语言:根据形参c中指定的英文字母,按顺序打印出若干后继相邻字母,-主函数中放入一个带头节点的链表结构中,h指向链表的头节点。fun函数找出学生的最高分-使用插入排序法对字符串中的字符进行升序排序。-从文件中找到指定学号的学生数据,读入次学生数据,
//根据形参c中指定的英文字母,按顺序打印出若干后继相邻字母,输出字母的大小与形参c一致,数量由形参d指定.例如:输入c为Y,d为4,则输出ZABC. #include <stdio.h> ...
- 对文本行进行排序,新增-d(目录排序),只对字母数字空格排序(TCPL 练习5-16)
文本行的排序用到了命令行参数以及多级指针,在要求只对字母数字空格进行排序时,关键的问题点是兼容-f命令参数,也就是排序的同时忽略大小写.由于在之前的练习中,我将忽略大小写的比较方法重新写了一个函数tr ...
- JS生成随机的由字母数字组合的字符串
前言 最近有个需求,是需要生成3-32位长度的字母数字组合的随机字符串,另一个是生成43位随机字符串. 方法一 奇妙的写法 1 Math.random().toString(36).substr( ...
- js随机生成字母数字组合的字符串 随机动画数字
效果描述: 附件中只有一个index.html文件有效 其中包含css以及html两部分内容 纯js生成的几个随机数字 每次都不重复,点击按钮后再次切换 使用方法: 1.将css样式引入到你的网页中 ...
随机推荐
- K8S中pod和container的资源管理:CPU和Memory
K8S中创建pod时,可以显示地指明包含的container的资源需求(resouce request和resource limit),通常是CPU和Memory(RAM). kube-schedul ...
- npm 使用阿里源
npm config set registry https://registry.npm.taobao.org/ npm config get registry 安装vue-cli 报错 npm in ...
- homebrew 安装node 切换node版本
注意:如果之前使用brew install node安装过node,需要先执行brew unlink node来'解绑'node 1.查找可用的node版本 brew search node 2.安装 ...
- Skywalking安装
https://www.cnblogs.com/duanxz/p/15602842.html
- 基于SDN控制器(ONOS)实现量子设备配置管理
基础知识 基于SDN控制器(ONOS)实现量子设备配置管理,首先选择合适的南向协议.OpenFlow与NETCONF是两个最适合企业网场景使用的协议.目前各大网络厂商的网络设备都已基本宣称支持NETC ...
- Blob下载
下载方式 const aBlob = new Blob( array, options ); export function downLoadFile(data: ArrayBuffer, fileN ...
- idea安装破解
转 一般都会去官网下载,官网地址IntelliJ IDEA,官网上对于不同的操作系统(windows,macOS,Linux)都有两个版本可供下载 3|0安装 确认已经安装好了 JDK ,每个IDEA ...
- Word09 会计电算化节节高升office真题
1.课程的讲解之前,先来对题目进行分析,首先需要在考生文件夹下,将Wrod素材.docx文件另存为Word.docx,后续操作均基于此文件,否则不得分. 2.这一步非常的简单,打开下载素材文件,在[文 ...
- c++ 继承访问控制初步
访问控制方式这里有篇很好的文章,其实内容也是总结c++primer上的内容 现在就按照这篇的文章举例进行学习. 思路 不同继承方式的影响主要体现在: 1.派生类成员对基类成员的访问控制. 2.派生类对 ...
- Unity 消息机制
最近有新项目需要和同事合作开发,他做UI 我做网络层,做着做着发现 如果我们要相对独立完成自己的开发任务,那我们的代码耦合得减少,不然 一个人代码有大改的时候,另一个人也要进行大幅修改,这样不便于后期 ...