Sort Method of C String by ASCII Code

  • 2021-12-13 08:59:49
  • OfStack

When doing data docking with banks, it involves signature verification and encryption during data transmission. In the data signature scheme, data items are required to be sorted in ascending order according to ASCII code according to attribute names. The sorting of ASCII code in C # is not as simple as it seems, and it will be into the pit by accident. Because the sort of C # is not sorted by ASCII code by default. For example, I have an array of strings and sort them.


string[] vv = { "1", "2", "A", "a", "B", "b" };
Array.Sort(vv); // Results  1 2 a A b B

If sorted by ASCII code, the order should be: 1, 2, A, B, a, b, and the actual result after sorting is: 1, 2, a, A, b, B. This means that the Sort () method is not sorted by ASCII code by default. After that, I also tested the sorting of OrderBy () in C #, and found that it is not sorted according to ASCII code by default.


string[] vv = { "1", "2", "A", "a", "B", "b" };
vv.OrderBy(x => x); // Results  1 2 a A b B

So since the default sort is not sorted by ASCII code, what should we do? Look at the following code, just add one more parameter to the original sorting method: string. CompareOrdinal. string. CompareOrdinal converts each character to a corresponding numeric value (for example, a converts to the numeric value 97) and then compares the numeric values.


Array.Sort(vv, string.CompareOrdinal); //ASCII Sort 

Note: I fell into this pit because I didn't know how to sort characters with ASCII code at first, so Baidu made one. The result is that this C # parameter is sorted from small to large according to ASCII code (lexicographic order). When I use this method, the bank verification step always fails. Debugging found that my sorted result is different from that of the bank.


Related articles: