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


Indents strings with a variable number of characters/strings


  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)

    '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


Dim text As String = "This is a test"

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


'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: 4224