Click here to Skip to main content
15,885,757 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.
0.00/5 (No votes)
17 Feb 2011CPOL 4K   2  
Using the .NET profiler, I compared ToggleCaseByRobertToggleCaseByJohnand my new one given below: static string ToggleCaseByCeChode(string s) { char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) { ...
Using the .NET profiler, I compared

  • ToggleCaseByRobert
  • ToggleCaseByJohn
  • and my new one given 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);
}


and I'm happy to say that ToggleCaseByCeChode wins by a landslide. :)

Given a 500 character length string and executing each routing 10k times:

Elapsed Exlusive Time ( Time spent in this function )       
ToggleCaseByJohn     797.60
ToggleCaseByRobert 715.80
ToggleCaseByCeChode 13.05



Note by Alexander Bell: This algorithm (ToggleCaseByCeChode) indeed provides significant, 5...6 times (!) performance boost against two others, and by far, is the absolute champion in this league of Toggle Case Algorithms!:thumbsup: Kudos to CeChode!

Also, online Algorithms efficiency comparison is available at: Toggle Case Algorithms[^]

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

 
-- There are no messages in this forum --