Split text in two columns in VB.NET

This is a function code snippet to split a text in to two or more columns in VB.NET.

It is converted from my previous posted: Split text into multiple columns in PHP

InputString – String to be split into columns
Columns – Number of columns
SplitString – String to look for to not split midtext etc

Example of how to use:
[code lang=”vb”]
Dim strColumns As String() = SplitIntoColumns(strText, 2, "<h2>")
strText = "<table><tr><td>" & strColumns(0) & "</td><td>" & strColumns(1) & "</td></tr></table>"

Code snippet:
[code lang=”vb”]
Function SplitIntoColumns(ByVal InputString As String, ByVal Columns As Integer, ByVal SplitString As String) As String()

‘ Source: http://blog.tjitjing.com

‘ Splits a string into x number of columns and returns result as an array of columns

‘ Parameters:
‘ $InputString String to be split into columns
‘ $Columns Number of columns
‘ $SplitString String to look for to not split midtext etc

‘ Change history:
‘ 2011-02-04/Max Version 1
‘ 2011-05-16/Max Version 1.2

Dim Output() As String
ReDim Output(0 To Columns – 1)

‘ Find middle of text
Dim ColLength As Integer = Len(InputString) / Columns

‘ Split into columns
Dim ColCount As Integer
Dim Pos As Integer, LastPos As Integer = 0
For ColCount = 1 To Columns

‘ Find $SplitString, position to cut
Pos = -1
If (LastPos + ColLength) < InputString.Length Then
Pos = InputString.IndexOf(SplitString, LastPos + ColLength)
End If
If Pos = -1 Then Pos = InputString.Length

‘ Cut out column
Output(ColCount – 1) = Mid(InputString, LastPos + 1, Pos – LastPos)

LastPos = Pos

Next ColCount

Return Output

End Function


[Edit: Updated function]

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *