What is the easiest way to change 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 hope there is a library call that I don't know about that will make this easier. I would also like to avoid having a list of all known alphabetical characters and comparing each character with what is on the list. Perhaps this can be done with regular expressions, but I don't know them very well. Thanks.
Thanks for the help. I created a line extension method for this, which is mostly inspired by Anthony Pegram's solution, but without LINQ. I think this provides 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); }
c # regex case-sensitive
still_dreaming_1
source share