C # the string is sorted by ASCII code. Note the pitfalls,

Source: Internet
Author: User

C # the string is sorted by ASCII code. Note the pitfalls,

Data authentication and encryption during data transmission are involved in data interconnection with banks. In the data signature scheme, data items are required to be sorted in ascending order according to the attribute names by ASCII code. The ASCII code sorting in C # is not as simple as it is on the surface, so it will be pitted accidentally. C # Is not sorted by ASCII code by default. For example, I have such a string array and then sort it.

String [] vv = {"1", "2", "A", "a", "B", "B"}; Array. sort (vv); // result 1 2 a A B B

 

For sorting by ASCII code, the order should be: 1, 2, A, B, a, and B. The actual sorting result is: 1, 2,, a, B, B. this means that the Sort () method is not sorted by ASCII code by default. Then I tested the order by () in C # and found that it is not sorted by ASCII code by default.

String [] vv = {"1", "2", "A", "a", "B", "B"}; vv. orderBy (x => x); // result 1 2 a A B B

 

So since the default sorting is not by ASCII code, what should we do? The following code adds the string. CompareOrdinal parameter to the original sorting method. String. CompareOrdinal converts each character into a corresponding value (for example, convert a to a value 97), and then compares the value.

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

 

Note: this is because Baidu did not know how to sort characters by ASCII code at first. The result is that the C # parameter is sorted in ascending order of ASCII code (lexicographically). When I use this method, the bank's signature verification step will never pass, debugging found that my sorted results are different from those of the bank. The bloggers in this blog may not have discovered this pitfall themselves.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.