含字母数字的字符串排序算法,仿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样式引入到你的网页中 ...
随机推荐
- ssh 免密访问
首先配置三台机器的hosts文件 填写需要配置的三台主机ip,然后命名,这里我写的时 t1 t2 t3 三台机器上都要配置hosts文件,要配置一样. 三台机器改完后保存退出 ping一下刚才配置的三 ...
- python手动安装包办法
首先去官网找知己需要的包,我这是以自己安装为例 先找需要安装的包然后看箭头准备下载 我这里选择的是tar压缩格式的点一下箭头指的地方会弹出下载按钮,之后下载即可 找到自己安装的python文件所在的位 ...
- HDLbits—— 3-input look-up-table
// a 3-input look-up-table // In this question, you will design a circuit for an 8x1 memory, // wher ...
- iview table添加input框,且校验
方法一 render渲染 { title: "用户名", key: "stockPrice", render: (h, params) => { retu ...
- axios进行图片上传
进行图片的上传,一定要注意headers的设置: headers:{"Content-Type":"multipart/form-data&quo ...
- Solution - ARC152D Halftree
首先 \(n\) 为偶数时无解,这是显然的,因为一次加两条边,总边数一定是偶数. 下面我们证明 \(n\) 为奇数时一定有解,直接进行构造. 首先将每一个点编号加上 \(k\) 再模 \(n\) 的答 ...
- 在vue js中for循环使用
在线免费图片压缩工具 前端技术站 1.for(let item of response.data.result) { 用item操作每一条数据. } item:定义的每一条的变量 response.d ...
- window 安装淘宝镜像
打开cmd, 输入如下命令 npm config set registry https://registry.npm.taobao.org 判断是否配置淘宝镜像成功 npm config get re ...
- 2.TS 的数据类型
一.定义变量 TS 中创建变量有四个要素: 定义变量的关键字:var.let.const 变量名 变量的数据类型 变量的初始值 语法结构如下: let 变量名: 数据类型 = 初始值 注意,变量的初始 ...
- python 读取ini文件内容
1 import configparser 2 cfgini = "D:\\123.ini" 3 conf = configparser.ConfigParser() 4 conf ...