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

Indent

Indents strings with a variable number of characters/strings

Source

<Extension()>
  Public Function Indent(str As String, length As Integer, Optional indentationCharacter As String = " ") As String

    'If string is nothing or the indentation length is 0 then return the unprocessed string
    If String.IsNullOrEmpty(str) OrElse length = 0 Then Return str

    Dim sb As New StringBuilder()

    'An indentation length smaller then 0 changes this function from an indent function to an append function.
    'For that the final string has to start of with the initial str.
    If length < 0 Then sb.Append(str)

    'Append the indentation string
    For i = 1 To Math.Abs(length)
      sb.Append(indentationCharacter)
    Next

    'If the indentation length was greater then 0 the string gets added now.
    If length > 0 Then sb.Append(str)

    Return sb.ToString

  End Function

Example

Dim text As String = "This is a test"

text.Indent(0)
text.Indent(10)
text.Indent(10, "-")
text.Indent(-10, "-")
text.Indent(5, "/\").Indent(-5, "/\")

'Results

'This is a test
'          This is a test
'----------This is a test
'This is a test----------
'/\/\/\/\/\This is a test/\/\/\/\/\

Author: noxon

Submitted on: 7 mrt 2013

Language: VB

Type: System.String

Views: 5506