2016-10-25 11 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; 
} 

は今、私は1つの方法として、小文字にまたはループのために内部の各文字を小文字に入力文字列を変換するように、ここでは物事のカップルを実行しようとしました。

文字列の下側の最初の方法は問題ありませんが、不変の文字列オブジェクトを変更していますので効率的な方法ではありません。私の2番目の方法は働いていますが、大きな文字列の場合に効率的かどうかはわかりません。

私の辞書の大文字小文字を区別しないようにするか、最も低い効率で文字列を小文字にすることについてのコメントはありますか?

+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私はそれを忘れました:/今すぐ固定、ありがとう。 –

関連する問題