Reverse case of all alphabetic characters in C# string
You could do it in a line with LINQ. One method:
string input = "aBc1$";
string reversedCase = new string(
input.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ?
char.ToLower(c) : char.ToUpper(c)) : c).ToArray());
If you don't care about internationalization:
string input = "aBc1$@[\\]^_{|{~";
Encoding enc = new System.Text.ASCIIEncoding();
byte[] b = enc.GetBytes(input);
for (int i = input.Length - 1; i >= 0; i -= 1) {
if ((b[i] & 0xdf) >= 65 && (b[i] & 0xdf) <= 90) { //check if alpha
b[i] ^= 0x20; // then XOR the correct bit to change case
}
}
Console.WriteLine(input);
Console.WriteLine(enc.GetString(b));
If, on the other hand, you DO care about internationalization, you'll want to pass in CultureInfo.InvariantCulture
to your ToUpper() and ToLower() functions...