話說 .NET String.Compare 很簡單就可以忽略大小寫...
但沒想到它有權重, 這導致一些問題,
比方說, 全形/半形的權重比英文字母小,
所以全形半形混雜的排序就會如同下面這樣:
abc
COACH
coach
coach2
COBCH
cox
ha
za
阿...那我要找 C 開頭的字, 都被全形拆開來啦,
這樣 String.Compare 能不能夠忽略全形/半形呢?
最後, 終於找到 CultureInfo.Compare 可以下 CompareOptions.IgnoreWidth ...
範例碼如下:
1: class Program
2: {
3:
4: static void Main(string[] args)
5: {
6: List<string> lst = new List<string>() {
7: "coach", "coach2", "COACH","COBCH","cox","ha","abc","za"
8: };
9:
10: lst.Sort((x, y) => CompareStr(x, y));
11:
12: foreach (string s in lst)
13: Console.WriteLine(s);
14:
15: Console.WriteLine("-----------");
16:
17: string f = "c";
18: int index = lst.BinarySearch(f, new compare());
19: if (index < 0)
20: {
21: index = ~index;
22: for (int i = index; i < lst.Count; i++)
23: {
24: if (CompareStr(lst[i],f, f.Length) == 0)
25: Console.WriteLine(lst[i]);
26: else
27: break;
28: }
29: }
30: Console.ReadLine();
31: }
32:
33: public static int CompareStr(string x, string y)
34: {
35: return CultureInfo.InvariantCulture.CompareInfo.Compare(x, y, CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase);
36: }
37:
38: public static int CompareStr(string x, string y, int len)
39: {
40: return CultureInfo.InvariantCulture.CompareInfo.Compare(x, 0, len, y, 0, len, CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase);
41: }
42: }
43:
44: class compare : IComparer<string>
45: {
46:
47: #region IComparer<string> 成員
48:
49: public int Compare(string x, string y)
50: {
51: return Program.CompareStr(x, y);
52: }
53:
54: #endregion
55: }
0 意見:
張貼留言