Naphstor Naphstor - 1 month ago 15
C# Question

Lower casing C# string

Hi all i have a small function that is storing characters in a string into a dictionary. The string could contain lower case and upper case letters simultaneously and I wanted to store all the characters in either lower case or upper case. Basically i want the dictionary to treat 'T' and 't' as same key. Below is my code.

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;
}


Now I tried to do couple of things here, like converting the input string to lower case as one way or to lower case each character inside for loop.

The first way of lower casing the string works fine, but I am modifying the immutable string object so may not be efficient way of doing. My second way is working but I am not sure if that is efficient in case of a large string.

Any comments on making my dictionary case insensitive or lower casing the string in most efficient way??

Answer

To create a case insensitive key dictionary, use the appropriate constructor:

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