Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

How to Toggle String Case in .NET

By , 23 Feb 2011
Rate this:
Please Sign up or sign in to vote.
I think if you just want to toggle the case of letters in some string, you don't need any special algorithms and sophisticated methods.
In fact, no matter what method you select, you must remember that POINTER is the fastest runner.
After reading all methods submitted above, I should say that the method actually is very simple. Take C# as an example, we can use the following method to toggle the string:
public static unsafe string ToggleString(string s)
    fixed (char* p = s)
        for (int i = 0; i < s.Length; i++)
            if (p[i] > 96 && p[i] < 123) p[i] -= (char)32;
            else if (p[i] > 64 && p[i] < 91) p[i] += (char)32;
    return s;
Upper case letters are from 65 to 90, and lower case ones are from 97 to 122. So the diff-value between one upper case letter and its lower counterpart is 32!
Let's test it with 1000,0000 loops, run it several times:
Stopwatch watch = new Stopwatch();
for (int i = 0; i < 10000000; i++)
The result is:
The average is 2790, about 3 seconds, how about your results ?


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

About the Author

Software Developer
China China
No Biography provided

Comments and Discussions

GeneralActually, in my browser, Alternate 13 is regular expression,... PinmemberYouzelin25-Feb-11 3:22 
GeneralRe: Yeah, it's possible that ordinal numbers are different for d... PinmemberDrABELL25-Feb-11 12:35 
General@Kevinyou- 1. Alternate 13 DOES NOT use the regular express... PinmemberDrABELL25-Feb-11 2:30 
GeneralAlternate 13 is the best? Do you read my alternate carefully... PinmemberKevinyou24-Feb-11 19:38 
GeneralHow to test? I just find a list of buttons to click, how can... PinmemberKevinyou24-Feb-11 19:27 
GeneralHi Kevinyou, 1. Michael Hansen already has posted the algor... PinmemberDrABELL24-Feb-11 2:34 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140421.2 | Last Updated 24 Feb 2011
Article Copyright 2011 by Kevinyou
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid