65.9K
CodeProject is changing. Read more.
Home

How to Toggle String Case in .NET

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Feb 22, 2011

CPOL
viewsIcon

8891

Following two Toggle Case Algorithms, implemented as "pure" .NET solution (no "unsafe" coding technique, all managed code) demonstrate the best performance, tested against a variety of text strings, containing: ASCII, Unicode, all Low case, all Upper case, long numeric strings

1. Ayoola-Bell Toggle Case Algorithm
(Originally posted by Henry Ayoola, modified by Alex Bell)
 

//======================================================
/// <summary>Ayoola-Bell Toggle Case Algorithm</summary>
/// <param name="s">string</param>
/// <returns>string</returns>
public static string ToggleCase_Ayoola_Bell(string s)
{
    char[] chs = s.ToCharArray();
    for (int i = s.Length - 1; i >= 0; i--)
    {
        char ch = chs[i];
        if (char.IsLetter(ch))
        {
            char foo = (char)(ch & ~0x20);
            if ((foo >= 0x41 && foo <= 0x5a) ||
                (foo >= 0xc0 && foo <= 0xde && foo != 0xd7))
                chs[i] = (char)(ch ^ 0x20);
            else if ((foo == 0xdf || ch > 0xff))
                chs[i] = char.IsLower(ch) ?
                         char.ToUpper(ch) :
                         char.ToLower(ch);
        }
    }
    return (new String(chs));
}
//=======================================================


The above algorithm is the fastest .NET solution; it implements the important char.IsLetter check prior to processing the text string, thus giving tremendous performance boost when converting the strings containing significant amount of non-letter characters.

Same technique is applied to the algorithm by Nedel resulted in elegant, rather simple yet effective .NET solution, trailing the first one in terms of performance: the difference is almost insignificant in case of processing the Unicode strings.

2. Bell-Nedel Toggle Case Algorithm
(Originally posted by Nedel, modified by Alex Bell)

//*******************************************************
/// <summary>Bell_Nedel Toggle Case Algorithm</summary>
/// <param name="s">string</param>
/// <returns>string</returns>
protected string ToggleCase_Bell_Nedel(string s)
{
    char[] charArr = s.ToCharArray();
    for (int i = 0; i < charArr.Length; ++i) {
        if (char.IsLetter(charArr[i]))
        {
            charArr[i] = char.IsLower(charArr[i]) ?
                         char.ToUpper(charArr[i]) :
                         char.ToLower(charArr[i]);
        }
    }
    return (new String(charArr));
}
//*********************************************************


Note: In terms of performance, the absolute speed champion in this "League of Extraordinary Efficient Toggle Case Algorithms" :) is the solution provided by Michael Hansen; be aware, that his solution is using "unsafe" coding technique, going beyond the boundaries of .NET managed code.