What is the simplest way to reverse the case of all alphabetic characters in a C# string? For example "aBc1$;" should become "AbC1$;" I could easily write a method that does this, but I am hoping there is a library call that I don't know about that would make this easier. I would also like to avoid having a list of all known alphabetic characters and comparing each character to what is in the list. Maybe this can be done with regular expressions, but I don't know them very well. Thanks.
Thanks for the help. I created a string extension method for this that is mostly inspired by Anthony Pegram's solution, but without the LINQ. I think this strikes a good balance between readability and performance. Here is what I came up with.
public static string SwapCase(this string source) {
char[] caseSwappedChars = new char[source.Length];
for(int i = 0; i < caseSwappedChars.Length; i++) {
char c = source[i];
if(char.IsLetter(c)) {
caseSwappedChars[i] =
char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
} else {
caseSwappedChars[i] = c;
}
}
return new string(caseSwappedChars);
}