1

【笨問題】C# 字串依 ASCII 排序

 1 year ago
source link: https://blog.darkthread.net/blog/cs-str-orderby-ascii/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【笨問題】C# 字串依 ASCII 排序

calendar.svg 2022-10-11 08:16 PM comment.svg 0 eye.svg 350

許多程式老骨腦袋都有這麼一張表,並且會背幾組特別數字:空白鍵是 32 (0x20),0 是 48 (0x30)、A 是 65 (0x41),加 32 可以變成 a 97 (0x61)...

Fig1_638010877292973018.png
圖片來源:維基百科

在 C# 做字串排序,一時恍忽,熊熊覺得 new[] { "Jeffrey","darkthread", } 排序 "J"effrey (ASCII 0x4a) 應該要排在 "d"arkthread (0x64) 前面,但事實不然:

Fig3_638010877294881060.png

猛然想起,.NET 字串排序先後是由 CultureInfo 決定,誰跟你 ASCII?(延伸閱讀:.NET 中文字串排序(筆劃、注音))

那... 如果我要依 ASCII 排序怎麼辦?請用 StringComparer.Ordinal,它還有個兄弟叫 StringComparer.OrdinalIgnoreCase,一樣依 ASCII,但不分大小寫,a 在 B 前面,A 在 a 前面。

寫段程式實測驗證:

void Main()
{
    var array = new[] { "0", "a", "b", "A", "B" };
	Action<IEnumerable<string>, string> dump = (a, n) => {
		Console.WriteLine(n);
		Console.WriteLine(new string('=', 36));
		Console.WriteLine(string.Join(" < ", a.ToArray()));
		Console.WriteLine();
	};
    
    dump(array, "Raw");
    Array.Sort(array);
    dump(array, "Sort");
    dump(array.OrderBy(o => o), "OrderBy");
    Array.Sort(array, StringComparer.Ordinal);
    dump(array, "Sort StringComparer.Ordinal");
    dump(array.OrderBy(o => o, StringComparer.Ordinal), 
		"OrderBy StringComparer.Ordinal");
	Array.Sort(array, StringComparer.OrdinalIgnoreCase);
	dump(array, "Sort StringComparer.OrdinalIgnoreCase");
}

Fig2_638010877296941874.png

打完收工。

  • Posted in
  • C#

and has 0 comments

Comments

Be the first to post a comment

Post a comment

Comment
Name Captcha 35 - 4 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK