65.9K
CodeProject is changing. Read more.
Home

How to Toggle String Case in .NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (4 votes)

Feb 9, 2011

CPOL
viewsIcon

9860

This does the same. (I'm not sure it's better, but I'm a fan of this style) :)static string toggle(string t){ return (from c in t select new string(Char.IsLower(c) ? Char.ToUpper(c) : Char.ToLower(c), 1)).Aggregate((a, b) => a += b);}much better performance than stringbuilder...

This does the same. (I'm not sure it's better, but I'm a fan of this style) :)
static string toggle(string t)
{
    return (from c in t select new string(Char.IsLower(c) ? Char.ToUpper(c) : Char.ToLower(c), 1)).Aggregate((a, b) => a += b);
}
much better performance than stringbuilder below
static string ToggleCaseByCeChode(string s)
{
     char[] chars = s.ToCharArray();
     for (int i = 0; i < chars.Length; i++)
     {
          if(chars[i]<65){}
          else if (chars[i] >122) { }
          else if (chars[i] > 90 && chars[i]<97) { }
          else if ((chars[i] & 32) == 32)
               chars[i] = (char)(chars[i] - 32);
          else
               chars[i] = (char)(chars[i] | 32);
     }
     return new String(chars);
}