Brandon Minner Brandon Minner - 3 years ago 89
C# Question

Why does C# .ToLower not change the ASCII value of the string?

I was trying to create a method to find the amount of duplicate characters in a string. So, for example,

would return 2 and
would also return 2. My first thought to create this method was to convert the whole string to lowercase and then count how many times the characters appear based on their ASCII values. So here is my code:

public static int DuplicateCount(string str)
int[] buffer = new int[128]; //128 possible ASCII characters
string lower = str.ToLower();
int dups = 0;

for (int i = 0; i < str.Length; i++)
int num = (int)str[i];
buffer[num]++; //increase
if (buffer[num] == 2)
return dups;

This method won't work when the string contains uppercase characters. The reason why this method doesn't work is because the
call does not change the ASCII value of the characters, even though the string itself is changed to all lower case. Does anyone know why this would be the case? And how would you get around it?

Answer Source

This happens because you used str instead of lower in your loop. ToLower() only returns a copy of a modified string (which you obviously saved, but didn't use).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download