Converting string to sortable number

Is there any way of converting a string value (any content) to a number such that they both sort in the same way? I don't need to be able to convert the number back to a string. In fact it would be an advantage if it were impossible to convert it back.

I don't need to be able to sort any length of string. If a 64-bit long integer is used as the sort-value then I could trim the texts to a value that fits this number range.

Answers


I don't think there can be 100% correct way since sorting a string depends on the culture. For ex

int c1 = String.Compare("AA", "BB", false, CultureInfo.GetCultureInfo("en-US")); //return -1
int c2 = String.Compare("AA", "BB", false, CultureInfo.GetCultureInfo("da-DK")); //return  1

The closest thing I can think of is:

ulong l = BitConverter.ToUInt64(Encoding.UTF8.GetBytes(str), 0);

PS: pad str if its len is shorter than 8


You could take the first 8 bytes from the string, the 8 bytes would make up a ulong. It would only be 4 characters of the string with unicode, or 8 characters if you limit the strings to ASCII.


Need Your Help

Reducing time complexity using HashMap, or is there a better method?

java algorithm hash hashmap complexity-theory

Right, this is from an older exam which i'm using to prepare my own exam in january. We are given the following method:

Use link words in a text in UITextView

ios objective-c xcode hyperlink uitextview

I`m starting in Objective-c this Year and I found nothing that could help me in the logic of how elaborate it:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.