noidea noidea - 1 year ago 62 Question

Split text in group of "x" characters

I need to split some text, but i'm having trouble with some extra spaces.
The following image shows the usual output text.


I want to add the split values in a checkedlistbox and i have the following code:

Dim SEPARATED = TextBox1.Text.Split(vbCr, vbLf, vbTab, ">") '" "C

For Each item In separated
If item <> "" Then CheckedListBox1.Items.Add(item)

Dim MODIFIED As String() = ANSWER.ToString.Split(" ")

buuuuuuut the extra spaces are giving me headaches. I don't know how to split the text in groups of twelve chars ( they're always 12, the spaces complete them) .

In conclusion, using the example, i want to only show "DEFAULT","EX W SPACE","POTATO" and "HELP PLS".

Thank you !

Answer Source

I used the GetOPString() function to return a string with your items in it (DEFAULT","EX W SPACE","POTATO" and "HELP PLS") with a padding of 12 characters. That function you do not need because your source string is already built like that.

I used the following logic

  1. Split source string into lines
  2. If there is a word with no space in front (EXAMPLE), It is some sort of title so I ignore it (you didn't want it in the final result)
  3. Trim word to remove all spaces and starting ">" character if found

See the example below.

You can tweak it according to your need.

Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    Dim Rawstring As String = GetOPString("DEFAULT","EX W SPACE","POTATO",">HELP PLS")
    Dim SEPARATED As List(Of String) = GetListItems(Rawstring)

    For Each Item As String In SEPARATED
End Sub

  ''' <summary>
''' Get a list of string by dividing Rawstring into 12 chars sequence. 
''' Any space is trimmed and leading > character (if found) is removed.
''' </summary>
''' <param name="RawString"></param>
''' <returns></returns>
Private Function GetListItems(RawString As String) As IEnumerable(Of String)
    Dim Output As New List(Of String)

    For Each item In RawString.Split(vbCr)
        If String.IsNullOrWhiteSpace(item) Then Continue For

        Dim AssumeTitle As Boolean = Not String.IsNullOrWhiteSpace(item(0))
        If AssumeTitle Then Continue For 'EXAMPLE is the title and we do not want it in the checkbox

        item = item.Trim.TrimStart(">"c)


    Return Output
End Function

''' <summary>
''' I used this function only to return the string you have in your post, 
''' which is, words to be separated in 12 characters sequences.
''' </summary>
''' <returns></returns>
Private Function GetOPString(ByVal ParamArray Words As String()) As String
    Dim Output As New Text.StringBuilder

    For Each Item As String In Words
        If Not Item.StartsWith(">") Then
            Output.Append(" ")
        End If

    Return Output.ToString
End Function