Click here to Skip to main content
Click here to Skip to main content
Go to top

Letter Case Conversion Algorithms: Title Case, Toggle Case

, 5 Mar 2011
Rate this:
Please Sign up or sign in to vote.
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
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
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).
 

Test Page

Test Page is available at: http://webinfocentral.com/resources/toggleCaseAlgorithm.aspx[^]. On that page, notice the check box allowing to select 2 different conversion options: either to convert all words to Title Case, or to keep the all-capital-lettered words intact.
 

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 most popular test editor, Microsoft Word). Plenty of various implementations of Toggle Case algorithms could be found at [3]; the project originated by CodeProject member Manas Bhardwaj was amended by multiple users, resulting in two most sophisticated Toggle Case algorithms (Ayoola-Bell Toggle Case Algorithm demonstrated the highest performance on selected test strings, trailed by Bell-Nedel Toggle Case Algorithm with similar performance and much simpler implementation), applicable to any ASCII/Unicode strings:
 
Listing 3. 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));
}
 
Listing 4. 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));
}
 

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[^]
4. Test Page[^]

License

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

Share

About the Author

DrABELL
President Infosoft International Inc
United States United States
Dr. A. Bell has 20+ years of Software and Electrical Engineering experience. He is Win/Web veteran, published 200+ articles and authored 37 inventions, currently focused on: Windows 7/8, HTML5, CSS3, jQuery, SQL, .NET, ASP.NET, WPF, C#, Speech Technology and Mobile apps. He's been among recent App submission winners (The Windows 8* & Ultrabook™ App Innovation Contest 2012). Sample pubs:
  1. Edumatter M12: School Math Calculators and Equation Solvers (contest winner)
  2. Engineering Calculator VOLTA-2013 (contest winner)
  3. HTML5 Best Practices: Table formatting via CSS3
  4. Edumatter-M12 for Windows, app overview
  5. Engineering Calculator VOLTA-814D
  6. CoolPhone: phone numbers-to-text converter
  7. SQL generates large data sequence
  8. Aggregate Product function extends SQL
  9. Top-50 Digital Cameras
  10. WebTV Project: Embedded YouTube Player (Goog #1 YouTube API for ASP.NET)
Dr. Bell is personally credited for 10+ Enterprise level projects (Finance/Investment, Engineering, Edu) w/total code base exceeding 250k lines; doing consulting in NYC for 20 yrs.
Follow on   Twitter

Comments and Discussions

 
GeneralRe: Manfred, This is the 2nd request to remove your unfair vote. PinmemberDrABELL1-Mar-11 9:02 
GeneralRe: Manfred- 1. I did not want to start this controversy: YOU we... PinmemberDrABELL28-Feb-11 4:21 
GeneralRe: DrABell, you are sorely wrong. I never trash anything. I'm s... PinmvpManfred R. Bihy27-Feb-11 20:50 
GeneralRe: Manfred, I am reading currently your profile info in public ... PinmemberDrABELL26-Feb-11 10:10 
GeneralRe: Regarding point 2.: So what! Either link to your alternates... PinmvpManfred R. Bihy26-Feb-11 9:36 
GeneralReason for my vote of 1 Your already posted this as an alter... PinmvpManfred R. Bihy26-Feb-11 8:08 
GeneralRe: Hi, Manfred 1. You are wrong: Title Case algorithm has not b... PinmemberDrABELL26-Feb-11 9:19 

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
Web04 | 2.8.140916.1 | Last Updated 6 Mar 2011
Article Copyright 2011 by DrABELL
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid