gpt4 book ai didi

c# - 列表的排序包含具有字母/数字的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:46 25 4
gpt4 key购买 nike

我想对包含按字母顺序排列的字符串、字母和数字以及数字的混合字符串的字符串进行排序列表。我的客户要求这样排序:

按表列表类型对象排序包含项目代码:111,111A,222,411G,300,411Z,G411,AG500,A111,AZ600,ABQ,ZZZ,AAN等

要求的结果:首先显示数字(如 111 然后 222 然后 300 等...) 接下来是带字母的数字(如 111A 然后 411G 然后 411Z 等...) 接下来是带数字的字母(如 A111 然后 G411 然后 AG500然后是 AZ600 等...)仅下一个字母(如 AAN 然后是 ABQ 然后是 ZZZ 等...)

所以字符串可以是任何东西。但我想根据需要的结果进行排序。所以请帮助我。

最佳答案

unsortedStringList.Sort(new AlphanumComparatorFastString());

AlphanumComparator:

    public class AlphanumComparatorFastString : IComparer<String>
{
public int Compare(string s1, string s2)
{
if (s1 == null)
return 0;

if (s2 == null)
return 0;

int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;

// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];

// Some buffers we can build up characters in for each chunk.
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;

// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;

if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

do
{
space2[loc2++] = ch2;
marker2++;

if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));

// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);

int result;

if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}

if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}

发现于 http://www.dotnetperls.com/alphanumeric-sorting

关于c# - 列表的排序包含具有字母/数字的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11896158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com