问题描述
我有一个文件名数组,我想通过数字式的排序,请给我一个解决方案。
例1:
原始数组: [name99.txt,name98.txt,name100.txt]
结果
排序的数组: [name98.txt,name99.txt,name100.txt]
结果
(使用字符串排序,排序的结果是 [name100.txt,name98.txt,name99.txt]
)
例2:
原始数组: [a99.txt,b98.txt,b100.txt]
结果
排序的数组: [a99.txt,b98.txt,b100.txt]
结果
(使用字符串排序,排序的结果是 [a99.txt,b100.txt,b99.txt]
)
的String [] = AR新的字符串[] {name99.txt,name98.txt,name100 。文本 };
的Array.Sort(AR,(A,B)=> int.Parse(Regex.Replace(一,[^ 0-9],)) - int.Parse(Regex.Replace(二,[ ^ 0-9],)));的foreach(AR中的一个变种)
Console.WriteLine(一);
以上假设您的文件传真名为 ###名。TXT
。对于真正的数字排序,请使用以下更复杂的版本:
公共静态无效NumericalSort(字符串[] AR)
{
正则表达式RGX =新的正则表达式(([^ 0-9] *)([0-9] +));
的Array.Sort(AR,(A,B)=>
{
变种MA = rgx.Matches(一);
VAR MB = rgx.Matches(B);
的for(int i = 0; I< ma.Count ++ I)
{
INT RET = MA [I] .Groups [1] .Value.CompareTo(MB [I] .Groups [1]。价值);
如果(RET!= 0)
返回RET; RET = int.Parse(MA [I] .Groups [2] .value的) - int.Parse(MB [I] .Groups [2]。价值);
如果(RET!= 0)
返回RET;
} 返回0;
});
}静态无效的主要(字串[] args)
{
字符串[] = AR新的字符串[] {a99.txt,b98.txt,b100.txt}; NumericalSort(AR); 的foreach(AR中的一个变种)
Console.WriteLine(一);
}
I have a filenames array, I want to sort it by numeric style, please give to me a solution.
Example1:
Original array: [name99.txt, name98.txt, name100.txt]
Sorted array: [name98.txt, name99.txt, name100.txt]
(Using string sorting, result of sorting is [name100.txt, name98.txt, name99.txt]
)
Example2:
Original array: [a99.txt, b98.txt, b100.txt]
Sorted array: [a99.txt, b98.txt, b100.txt]
(Using string sorting, result of sorting is [a99.txt, b100.txt, b99.txt]
)
string[] ar = new string[] { "name99.txt", "name98.txt", "name100.txt" };
Array.Sort(ar, (a, b) => int.Parse(Regex.Replace(a, "[^0-9]", "")) - int.Parse(Regex.Replace(b, "[^0-9]", "")));
foreach (var a in ar)
Console.WriteLine(a);
The above assumed that your files are allways called name###.txt
. For the real numeric sorting use the following more complicated version:
public static void NumericalSort(string[] ar)
{
Regex rgx = new Regex("([^0-9]*)([0-9]+)");
Array.Sort(ar, (a, b) =>
{
var ma = rgx.Matches(a);
var mb = rgx.Matches(b);
for (int i = 0; i < ma.Count; ++i)
{
int ret = ma[i].Groups[1].Value.CompareTo(mb[i].Groups[1].Value);
if (ret != 0)
return ret;
ret = int.Parse(ma[i].Groups[2].Value) - int.Parse(mb[i].Groups[2].Value);
if (ret != 0)
return ret;
}
return 0;
});
}
static void Main(string[] args)
{
string[] ar = new string[] { "a99.txt", "b98.txt", "b100.txt" };
NumericalSort(ar);
foreach (var a in ar)
Console.WriteLine(a);
}
这篇关于如何排序数字式的字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!