How to Format a String in Proper Case or Title Case in VB.NET

Introduction:

This article describes a simple approach to covert a string to the proper case or title case as was available in previous versions of Visual Basic.  This function is only a few lines of code but will return any string with the first letter of each word in upper case while all other letters are in lower case.  The function shown may be of use if you have an application that receives data in upper or lower case format and needs to be shown in title case or proper case.

The Code:

The code is very simple and does not require much of an explanation.  Basically, all that is done, is the receiving string is split into multiple strings using the space character as the delimiter.  Then a loop iterates through each word and capitalizes the first letter of each word.  Then the rest of the letters in each iterated string is converted to lower case.  After all the words have been iterated through the return string is built and then finally returned in proper or title case.  The code is located below:

Public Shared Function ToProper(ByVal Str As String) As String

' Author:      James Mouchett
' Build Date:  March 16, 2009
' Use:         To format a string to proper case / title case without the
'              need of the visualbasic.dll (VB6) namespace.

 

' Storage String For Output
Dim OutStr As String = String.Empty

' Used For Holding Each Word Separated By A Space
Dim Words() As String = Split(Str, " ")

' Loop Through All The Words In The String
For A = 0 To Words.GetUpperBound(0)

     ' Retrieve The Word In The Words Array For Processing
    
Dim TempWord As String = Words(A)

     ' Loop Through All The Characters In The String
    
For B = 0 To TempWord.Length - 1

          If B = 0 Then
               ' Make The First Character Uppercase
              
OutStr += Char.ToUpper(TempWord(B))
          Else
              
' Make The Other Characters Lowercase
              
OutStr += Char.ToLower(TempWord(B))
          End If

         
' Add Spaces If Any Are Necessary
         
If A <> Words.GetUpperBound(0) And B = TempWord.Length - 1 Then
               OutStr += " "
         
End If

     Next
Next

' Return Formatted String
Return OutStr

End Function

Summary:

In whole, this is almost like the .ToProper or StrConv(ToProper) function from the visualbasic.dll or VB6 namespace.  However, this function was written with the intention of removing the dependency of the VB6 namespace and to further utilize the .NET OOP programming style instead.


Similar Articles