C#自定义排序字符串IComparer [英] C# Custom Sort String IComparer
问题描述
我想更改字符串的排序方式,使其基于以下字母:
I want to change the sorting of strings so it is based off the following alphabet:
A,E,I,O,U,F,G,L,M,N,P,S,T,V,H,K,R
A,E,I,O,U,F,G,L,M,N,P,S,T,V,H,K,R
代替标准的A,B,C,D ... X,Y,Z
Instead of the standard A,B,C,D ... X,Y,Z
所以我开始尝试创建一个IComparer,但坚持如何实现.
So I started to try and create a IComparer but stuck on how to implement.
这是我到目前为止所获得的并没什么.
Here is what I got so far which ain't much.
public class CustomSort : IComparer<string>
{
public int Compare(string a, string b)
{
return 1;
}
}
任何帮助将不胜感激.
推荐答案
应该是这样的:
最后,您逐个字符地进行比较,在 Order
字符串中找到字符的索引".也许为了加快速度,您可以将 Order
字符串转换为 Dictionary< char,int>
,其中 int
是权重"./p>
In the end you compare character by character, finding the "index" of the character inside a Order
string. Perhaps to speed it up you could convert the Order
string to a Dictionary<char, int>
where the int
is the "weight".
public class CustomSort : IComparer<string>
{
public const string Order = "AEIOUFGLMNPSTVHKR";
public int Compare(string a, string b)
{
if (a == null)
{
return b == null ? 0 : -1;
}
if (b == null)
{
return 1;
}
int minLength = Math.Min(a.Length, b.Length);
for (int i = 0; i < minLength; i++)
{
int i1 = Order.IndexOf(a[i]);
int i2 = Order.IndexOf(b[i]);
if (i1 == -1)
{
throw new Exception(a);
}
if (i2 == -1)
{
throw new Exception(b);
}
int cmp = i1.CompareTo(i2);
if (cmp != 0)
{
return cmp;
}
}
return a.Length.CompareTo(b.Length);
}
}
这篇关于C#自定义排序字符串IComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!