Click here to Skip to main content
15,885,365 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

How to Toggle String Case in .NET

Rate me:
Please Sign up or sign in to vote.
4.86/5 (4 votes)
15 Feb 2011CPOL 9K   2   4
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) :)

C#
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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 I love the compact. Pin
LongTTH22-Feb-11 3:43
LongTTH22-Feb-11 3:43 
GeneralReason for my vote of 5 VERY NICE Pin
gokhan_ertastr14-Feb-11 20:03
gokhan_ertastr14-Feb-11 20:03 
General"Clickable" link to the test page: &lt;a href="http://bit.ly... Pin
DrABELL10-Feb-11 7:59
DrABELL10-Feb-11 7:59 
GeneralI've built the test page to compare two Algorithms, provided... Pin
DrABELL10-Feb-11 7:35
DrABELL10-Feb-11 7:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.