views:

179

answers:

4

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);
}
+6  A: 

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());
Anthony Pegram
I like this, thanks!
INTPnerd
@INTPnerd If things turn up slow you might look into other methods...
Emtucifor
+1  A: 

You could do it old-school if you don't know LINQ.

static string InvertCasing(string s)
{
    char[] c = s.ToCharArray();
    char[] cUpper = s.ToUpper().ToCharArray();
    char[] cLower = s.ToLower().ToCharArray();

    for (int i = 0; i < c.Length; i++)
    {
        if (c[i] == cUpper[i])
        {
            c[i] = cLower[i];
        }
        else
        {
            c[i] = cUpper[i];
        }
    }

    return new string(c);
}
Michael Covelli
+1  A: 

Here's a regex approach:

string input = "aBcdefGhI123jKLMo$";
string result = Regex.Replace(input, "[a-zA-Z]",
                            m => Char.IsUpper(m.Value[0]) ?
                                 Char.ToLower(m.Value[0]).ToString() :
                                 Char.ToUpper(m.Value[0]).ToString());
Console.WriteLine("Original: " + input);
Console.WriteLine("Modified: " + result);

You can use Char.Parse(m.Value) as an alternate to m.Value[0]. Also, be mindful of using the ToUpperInvariant and ToLowerInvariant methods instead. For more info see this question: In C# what is the difference between ToUpper() and ToUpperInvariant()?

Ahmad Mageed
+3  A: 

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...

Emtucifor
This is a good trick with the XOR that a lot of people don't know about. Any letter XORed by 32 (0x20) will yield the reverse case.
Kibbee
@Kibbee thanks for explaining. I probably should have in my post. Anyway, this trick only works for plain old ASCII characters...
Emtucifor