2016-10-25 44 views
-2

大家好,我有一個小函數,將字符串中的字符存儲到字典中。字符串可以同時包含小寫字母和大寫字母,我希望以小寫或大寫形式存儲所有字符。基本上我想讓字典把'T'和't'當作同一個鍵。以下是我的代碼。下殼C#字符串

public bool CheckCharOddCount(string str1) 
{ 
    bool isOdd = false; 
    Dictionary<char, int> dt = new Dictionary<char, int>(); 

    // Dictionary is case sensitive so 'T' and 't' are treated as different keys.  
    str1 = str1.ToLower(); # One way 
    foreach (char c in str1) 
    { 
    c = char.ToLower(c);  # Another way 
    if (dt.ContainsKey(c)) 
     dt[c]++; 
    else 
     dt.Add(c, 1); 
    } 

    foreach (var item in dt) 
    { 
    if (item.Value % 2 == 1) 
    { 
     if (isOdd) 
     return false; 
     isOdd = true; 
    } 
    } 

    return true; 
} 

現在我試着做幾件事情在這裏,像轉換輸入的字符串爲小寫的一種方式或內部小寫每個字符for循環。

下套管的第一種方式字符串工作正常,但我修改了不可變字符串對象,因此可能不是有效的方式。我的第二種方法是工作,但我不確定在大字符串的情況下這是否有效。

任何意見使我的字典不區分大小寫或以最有效的方式降低字符串?

+5

S現在,在使用'ToLower'之前,請閱讀http://haacked.com/archive/2012/07/05/turkish-i-problem-and-why-you-should-care.aspx/和https ://blog.codinghorror.com/whats-wrong-with-turkey/ –

+0

你必須做'c = char.ToLower(c);'才能工作。 – juharr

回答

1

要創建一個不區分大小寫鍵的字典,使用適當的constructor

Dictionary<string, int> dictionary = new Dictionary<string, int>(
     StringComparer.CurrentCultureIgnoreCase); 
+1

我們沒有足夠的信息來了解字符串是否對文化敏感,但答案很可能是CurrentCultureIgnoreCase或OrdinalIgnoreCase。使用InvariantCulture通常是一個錯誤。見http://stackoverflow.com/questions/492799/difference-between-invariantculture-and-ordinal-string-comparison –

+0

@PsychomaticComplexity你是正確的,我修好了。 –

-1

如果你使用英語處理而已,這oneliner將做的工作:

string s = "AaaaAcWhatever"; 
Dictionary<char, int> dic = s.GroupBy(c => char.ToLower(c)) 
          .Select(g => new { Key = g.Key, Count = g.Count()}) 
          .ToDictionary(x => x.Key.First(), x => x.Count); 

輸出:

Count = 8 
[0]: {[a, 6]} 
[1]: {[c, 1]} 
[2]: {[w, 1]} 
[3]: {[h, 1]} 
[4]: {[t, 1]} 
[5]: {[e, 2]} 
[6]: {[v, 1]} 
[7]: {[r, 1]} 
+0

爲什麼不按'char.ToLower(c)'分組並避免中間字符串? – juharr

+0

@juharr我忘了:/現在修好了,謝謝。 –