Naphstor Naphstor - 1 month ago 4
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)
{
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 another way of lower casing each character inside loop doesn't work. Not sure if that is the correct usage or not. I read at msdn site here and the usage seems correct to me. Though the output of the Console.WriteLine(...) in msdn example is "a" which is string type not character. Is my understanding of msdn example correct??

Next I wanted to know, if my way of lower casing in my code is correct or not? If it is then is this efficient way of doing it?

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);
Comments