含字母数字的字符串排序算法,仿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样式引入到你的网页中 ...
随机推荐
- 【Ubuntu】设置桌面文件夹路径
Ubuntu 系统会将桌面文件夹路径默认设置为 $HOME/Desktop,包括文档.下载.图片等文件夹路径都有各自的默认路径.若想更改这些文件夹路径,可参考『此链接』. 首先到希望更改的路径下建立桌 ...
- Java中的左移、右移详细分析
转自csdn--https://blog.csdn.net/weixin_42408447/article/details/125914449 前提:<<(左移),>>(右移) ...
- Visual Studio 2010安装
学校要计算机二级证书,为了准备c语言的二级考试,要装Visual Studio 2010(Visual Studio 2022生成的文件过不了检测) 1-下载安装包 在这个网站上下载安装包 MSDN, ...
- 【转载】win10怎么设置窗口护眼?
转载地址:http://www.downza.cn/xy/122656.html win10设置窗口护眼模式的方法 2021-04-13 13:30:54来源:下载之家作者:down 小伙伴们你们知道 ...
- vmware 二次虚拟化
在创建的虚拟机的目录内找到扩展名为vmx的文件,在文件的最后添加 hypervisor.cpuid.v0 = "FALSE" 保存 重新打开虚拟机在 在虚拟机配置开启虚拟化
- nginx调试和location用法,匹配url
1.nginx调试输出内容到页面 location = /demo { charset utf-8; default_type text/html; return 500 "服务正在升级,请 ...
- python实现图片转PDF
import os from PIL import Image from reportlab.pdfgen import canvas def image_resize(img, width, hei ...
- 2022-04-18内部群每日三题-清辉PMP
1.在为一个有预算限制的项目生成状态报告时,项目经理发现该项目比进度计划落后一周.若要将项目拉回正轨,项目经理应该怎么做? A.重新分配关键路径活动的团队成员. B.向项目发起人要求额外的时间. C. ...
- (jmeter笔记)聚合报告分析
Label:说明是请求类型,如Http, FTP等请求. #Samples:也就是图形报表中的样本数目,总共发送到服务器的样本数目. Average:也就是图形报表中的平均值,是总运行时间除以发送到服 ...
- linux 设置开机自动挂载文件系统
一./etc/ 下增加rc.local文件(ubuntu默认没有这个文件) kuaibang@face:~$ sudo touch rc.local 二.安装NFS客户端 a.如果您使用CentOS. ...