Click here to Skip to main content
15,868,016 members
Articles / General Programming / Algorithms
Tip/Trick

Letter Case Conversion Algorithms: Title Case, Toggle Case

Rate me:
Please Sign up or sign in to vote.
4.89/5 (4 votes)
5 Mar 2011CPOL2 min read 31.4K   4   7
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)


Written By
Engineer
United States United States
Dr. Alexander Bell (aka DrABell), a seasoned full-stack Software (Win/Web/Mobile) and Data Engineer holds PhD in Electrical and Computer Engineering, authored 37 inventions and published 100+ technical articles and developed multiple award-winning apps (App Innovation Contests AIC 2012/2013 submissions) Alexander is currently focused on Microsoft Azure Cloud and .NET 6/8 development projects.

  1. HTML5/CSS3 graphic enhancement: buttons, inputs
  2. HTML5 Tables Formatting: Alternate Rows, Color Gradients, Shadows
  3. Azure web app: Engineering Calculator VOLTMATTER
  4. Azure: NYC real-time bus tracking app
  5. Quiz Engine powered by Azure cloud
  6. 'enRoute': Real-time NY City Bus Tracking Web App
  7. Advanced CSS3 Styling of HTML5 SELECT Element
  8. Aggregate Product function extends SQL
  9. YouTube™ API for ASP.NET

Comments and Discussions

 
GeneralRe: Manfred, This is the 2nd request to remove your unfair vote. Pin
DrABELL1-Mar-11 9:02
DrABELL1-Mar-11 9:02 
GeneralRe: Manfred- 1. I did not want to start this controversy: YOU we... Pin
DrABELL28-Feb-11 4:21
DrABELL28-Feb-11 4:21 
Manfred-
1. I did not want to start this controversy: YOU were the first who did! Thus, it is not "attack" from my side, but just a defense against such profoundly unfriendly behavior (re: your vote of 1 in regards to the useful article).
2. If you have published at least one article, or even small tips, then you would better understand the feelings of the authors, and significance of their work, and the ethics of online collaboration; probably you should start with your own development article before trashing other member's work ("trashing" in this context is pretty much accurate term to describe such unfair, subjective and unfriendly attitude to the work of others, re: your vote of 1)
3. Now, please remove you shameful vote, or provide the objective, fair and unbiased one.
GeneralRe: DrABell, you are sorely wrong. I never trash anything. I'm s... Pin
Manfred Rudolf Bihy27-Feb-11 20:50
professionalManfred Rudolf Bihy27-Feb-11 20:50 
GeneralRe: Manfred, I am reading currently your profile info in public ... Pin
DrABELL26-Feb-11 10:10
DrABELL26-Feb-11 10:10 
GeneralRe: Regarding point 2.: So what! Either link to your alternates... Pin
Manfred Rudolf Bihy26-Feb-11 9:36
professionalManfred Rudolf Bihy26-Feb-11 9:36 
GeneralReason for my vote of 1 Your already posted this as an alter... Pin
Manfred Rudolf Bihy26-Feb-11 8:08
professionalManfred Rudolf Bihy26-Feb-11 8:08 
GeneralRe: Hi, Manfred 1. You are wrong: Title Case algorithm has not b... Pin
DrABELL26-Feb-11 9:19
DrABELL26-Feb-11 9:19 

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

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