简体   繁体   中英

Alphanumeric string sorting with prifix and suffix

I have a alphanumeric string of array which contains some characters at end of string also. The problem is i'm able to sort only till before the last character. Here is the my array

string[] ar = new string[] { "DV00154A", "DV00144A", "DV00111B", "DV00100A", "DV00199B", "DV00001A" };

i have tried some method but the sorted array skipping the sorting of last character. here is one of the approach which i have tried.

public static string ArraySort(string input)
{
  return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10,'0'));
}

public static void Main(string[] args)
{
  string[] ar = new string[] { "DV00154A", "DV00144A", "DV00111B", "DV00100A", 
  "DV00199B", "DV00001A" };
  var result = ar.OrderBy(x => ArraySort(x));
  Console.WriteLine(string.Join(",",result.ToArray()));
 }

which returning the below output

DV00001A,DV00100A,DV00111B,DV00144A,DV00154A,DV00199B

but the output i need should be like this

DV00001A,DV00100A,DV00144A,DV00154A,DV00111B,DV00199B

What about this solution:

public static string ArraySort(string input)
{
    return $"{input.Substring(0, 2)}{input.Substring(7, 1)}{input.Substring(2, 5)}";
}

public static void Main(string[] args)
{
    string[] ar = new string[] { "DV00154A", "DV00144A", "DV00111B", "DV00100A", "DV00199B", "DV00001A" };
    Array.Sort(ar, (a, b) => StringComparer.OrdinalIgnoreCase.Compare(ArraySort(a), ArraySort(b)));
    Console.WriteLine(string.Join(",", ar));
    Console.ReadKey();
}

The ArraySort method rearranges the values in a sortable format: DV00154A -> DVA00154 . That values are used the by the Array.Sort comparer method.

The only disadvantage that the ar array is sorted in-place...

Edit:

I found an even better solution: just take my ArraySort method with your Main method. Should work just fine. :) And it will not affect your ar array.

Edit 2:

Just fixed a little bug in my ArraySort method. (Sorry.)

Edit 3:

If you can ignore the DV -prefix, you could change the ArraySort method to this:

public static string ArraySort(string input)
{
    return $"{input.Substring(7, 1)}{input.Substring(2, 5)}";
}

The logic is less complex and the resulting values are shorter. It should have a (marginal) better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM