Indent

  <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/\/\/\/\/\

Description

Indents strings with a variable number of characters/strings

Details

Double click on the code to select all.

 

;