ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ExpandToWords

Expand a string such as a field name by inserting a space ahead of each capitalized letter (where none exists).

Source

''' <summary>
''' Expand a string such as a field name by inserting a space ahead of each capitalized letter (where none exists). 
''' </summary>
''' <param name="inputString"></param>
''' <returns>Expanded string</returns>
''' <remarks></remarks>
<Extension()>
Public Function ExpandToWords(ByVal inputString As String) As String
    If inputString Is Nothing Then Return Nothing
    Dim charArray = inputString.ToCharArray
    Dim outStringBuilder As New StringBuilder(inputString.Length + 10)
    For index = 0 To charArray.GetUpperBound(0)
        If Char.IsUpper(charArray(index)) Then
            'If previous character is also uppercase, don't expand as this may be an acronym.
            If (index > 0) AndAlso Char.IsUpper(charArray(index - 1)) Then
                outStringBuilder.Append(charArray(index))
            Else
                outStringBuilder.Append(String.Concat(" ", charArray(index)))
            End If
        Else
            outStringBuilder.Append(charArray(index))
        End If
    Next

    Return outStringBuilder.ToString.Replace("_", " ").Trim

End Function

Example

Dim columnHeader as String = tableColumn.Name.ExpandToWords

Author: Udaya Amaradasa

Submitted on: 30 sep. 2014

Language: VB

Type: String

Views: 4195