Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / algorithm

Letter Case Conversion Algorithms: Title Case, Toggle Case

4.89/5 (4 votes)
5 Mar 2011CPOL2 min read 32.8K  
Algorithms extending the System.Globalization.TextInfo.ToTitleCase Method

Introduction

System.Globalization namespace contains useful TextInfo.ToTitleCase() method, enabling words capitalization, i.e. title case conversion, like: "What you see is what you get" into "What You See Is What You Get". The usage is rather straightforward and takes just a single line of code:

Listing 1

C#
string strTitleCase = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s)

where s - is the original string and strTitleCase is a new string, corresponding to the converted title case original string.
 

Method Extension

In case the original string contains the words, typed in all capital (Upper case) letters, then the conversion will not apply, thus the sample sentence: "HEY DUDE, THIS FOOD IS GOOD!" will stay the same. This logic prevents, for example, the acronyms/abbreviation to be converted, so "WYSIWYG" will be kept intact, presented in original format.

It would be useful to extend this built-in method with the ability to select the conversion options: convert all words, or to skip all capital lettered words. Following is the sample function, which does the job. If boolean all is set to false, then it performs just the built-in ToTitleCase(s) conversion; otherwise, it first converts all letters to Low Case using simple s.ToLower() method, and then applies the ToTitleCase(s) method:

Listing 2

C#
public static string TitleCase(string s, bool all)
{
    return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(all?s.ToLower():s);
}


The entire solution is extremely, simple: just replacing string argument s with (all?s.ToLower():s). By applying this modified method to the original phrase "HEY DUDE, THIS FOOD IS GOOD!", it will appear as: "Hey Dude, This Food Is Good!"; thus, all words will be properly capitalized. This extended method is universally applicable to any ASCII and Unicode strings as well (beware: acronyms will be processed as well if flag all is set to true).

Potential Issues

Beware that both methods (original built-in and modified one) could cause some issues when dealing with math formulas, like: 2x+3y=xy could become 2X+3Y=Xy after conversion. It is possible to create another method extension to cover this issue as well, though the potential complexity and performance degradation would probably outweigh the practical advantages of such algorithm, aimed at this particular rare case issue.

Toggle Case Algotithms

Toggle Case is another useful string conversion algorithm (as FYI: such feature along with TitleCase are both included in Microsoft Word). Two time-efficient Toggle Case algorithms applicable to any ASCII/Unicode strings are listed below: Ayoola-Bell Toggle Case Algorithm demonstrated the highest performance on selected test strings, trailed by Bell-Nedel Toggle Case Algorithm with similar performance and simpler implementation:

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

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


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

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

 

ToUpper() and ToLower()

ToUpper() and ToLower() represents two well-known and widely-used letter-case conversion functions, applicable to any ASCII and Unicode strings as well; they are included in the solutions corresponding to Listings 2, 3 and 4.

References

1. TextInfo.ToTitleCase Method[^]
2. How to convert string to lowercase, uppercase, or title (proper) case...[^]
3. How to Toggle String Case in .NET[^]

License

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

License

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