Text Splitting – Split In Chunk
Splits a long string into smaller chunks without breaking words, based on a specified maximum chunk length.
Words are kept whole, and no chunk will split a word in half. If adding a word would exceed the chunk length, the current chunk is closed and a new one is started. The resulting chunks are returned in the original order.
VB
Public Function SplitInChunk(ByVal TextToSplit As String,
ByVal LenghtOfChunk As Integer) As String()
Dim returnQueue As New System.Collections.Queue
Dim words As String() = TextToSplit.Split(" ".ToCharArray)
Dim currentChunk As String = ""
Dim arString() As String = Nothing
Dim index As Integer = 0
For index = 0 To words.GetUpperBound(0)
Dim currentWord As String = words(index)
If currentChunk.Length + currentWord.Length <= LenghtOfChunk Then
'The phrase is still short enough
currentChunk += " " & currentWord
Else
'The phrase would be too long
'Add the chunk to the list
returnQueue.Enqueue(currentChunk)
'Start a new chunk
currentChunk = currentWord
End If
Next index
'Reached the end. Add the last chunk to the list
returnQueue.Enqueue(currentChunk)
index = 0
For Each chunk As String In returnQueue
ReDim Preserve arString(index)
arString(index) = chunk
index = index + 1
Next
Return arString
End Function