Click here to Skip to main content
15,903,632 members
Articles / Programming Languages / C#
Tip/Trick

Title Case in VB.net or C#

Rate me:
Please Sign up or sign in to vote.
2.60/5 (3 votes)
29 Jun 2015CPOL 14.6K   3   2
Format book titles or TV series titles as the MLA style.

Introduction

Format book titles or TV series titles as the MLA style. 

Background

Today, I was writing a function dealing with title case.

I firstly tried to look for code in C# which deals with it, but all I found was actually first-letter-capital solutions. Like this one in StackOverFlow.com.

http://stackoverflow.com/questions/1206019/converting-string-to-title-case-in-c-sharp

 

However, what I wanted was first-letter-capital but escape words such as the, a, in, of, and words like USA, UK, TV should be all capital. Or to say I wanted the MLA(Modern Language association) style. The official definition is here:

https://www.ivcc.edu/stylebooks/stylebook4.aspx?id=14718

Capitalizing Titles

Capitalize the first letter of the major words of titles. Minor words, such as articles, prepositions, and coordinating conjunctions, are not capitalized unless they are the first word of a title or subtitle.

"Why Boys Don’t Play with Dolls" (a short essay) 

In the Heat of the Night (a film)

I finally found the functionality that I wanted but not the code.

http://www.titlecase.com/

Using the code

Unfortunately, I had to write the code by myself, and I meant to follow the MLA style. For the acronyms, because my project was related to TV shows so words such as US, UK, BBC are frequently used. You can modify the list and add your own acronyms.

VB.NET
<Extension()>
Public Function ToTitleCase(ByRef s As String) As String

    Dim upperCase = s.ToUpper()
    Dim words = upperCase.Split(" ")

    'prepositions, articles and conjunctions
    Dim minorWords = New String() {"ON", "IN", "AT", "OFF", "WITH", "TO", "AS", "BY",
                                   "THE", "A", "OTHER", "ANOTHER",
                                   "AND", "BUT", "ALSO", "ELSE", "FOR", "IF"}
    'countries, TV stations and others
    Dim acronyms = New String() {"UK", "USA", "US",
                                   "BBC",
                                   "TV"}

    'The first word.
    'The first letter of the first word is always capital.
    If acronyms.Contains(words(0)) Then
        words(0) = words(0).ToUpper()
    Else
        words(0) = words(0).ToPascalCase()
    End If

    'The rest words.
    For i As Integer = 1 To words.Length - 1
        If minorWords.Contains(words(i)) Then
            words(i) = words(i).ToLower()
        ElseIf acronyms.Contains(words(i)) Then
            words(i) = words(i).ToUpper()
        Else
            words(i) = words(i).ToPascalCase()
        End If
    Next

    Return String.Join(" ", words)

End Function

<Extension()>
Public Function ToPascalCase(ByRef s As String) As String
    Return s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower()
End Function

Test Cases

VB.NET
<TestMethod()>
Public Sub ToTitleCaseTest()
    Debug.Print("USA".ToTitleCase())
    Debug.Print("usa".ToTitleCase())
    Debug.Print("uSa".ToTitleCase())
    Debug.Print("Sleepy Hollow".ToTitleCase())
    Debug.Print("Z Nation".ToTitleCase())
    Debug.Print("Hot In Cleveland".ToTitleCase())
    Debug.Print("HOT IN CLEVELAND".ToTitleCase())
    Debug.Print("once upon a time".ToTitleCase())
    Debug.Print("ONCE UPON A TIME".ToTitleCase())
End Sub

Test Result

USA

USA

USA

Sleepy Hollow

Z Nation

Hot in Cleveland

Hot in Cleveland

Once Upon a Time

Once Upon a Time

C# Code

C#
public static class StringExtensions
{
    public static string ToTitleCase(this string s)
    {

        var upperCase = s.ToUpper();
        var words = upperCase.Split(' ');

        var minorWords = new String[] {"ON", "IN", "AT", "OFF", "WITH", "TO", "AS", "BY",//prepositions
                                   "THE", "A", "OTHER", "ANOTHER",//articles
                                   "AND", "BUT", "ALSO", "ELSE", "FOR", "IF"};//conjunctions

        var acronyms = new String[] {"UK", "USA", "US",//countries
                                   "BBC",//TV stations
                                   "TV"};//others

        //The first word.
        //The first letter of the first word is always capital.
        if (acronyms.Contains(words[0]))
        {
            words[0] = words[0].ToUpper();
        }
        else
        {
            words[0] = words[0].ToPascalCase();
        }

        //The rest words.
        for (int i = 0; i < words.Length; i++)
        {
            if (minorWords.Contains(words[i]))
            {
                words[i] = words[i].ToLower();
            }
            else if (acronyms.Contains(words[i]))
            {
                words[i] = words[i].ToUpper();
            }
            else
            {
                words[i] = words[i].ToPascalCase();
            }
        }

        return string.Join(" ", words);

    }

    public static string ToPascalCase(this string s)
    {
        return s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();
    }
}

 

License

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


Written By
Team Leader
Taiwan Taiwan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionTests could be done better Pin
John Brett30-Jun-15 2:14
John Brett30-Jun-15 2:14 
AnswerRe: Tests could be done better Pin
juwikuang14-Oct-15 22:57
juwikuang14-Oct-15 22:57 

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.