Home > OS >  How to split string into a lines in a particular sequence
How to split string into a lines in a particular sequence

Time:09-16

I have a list of members with their stats and i need to split it by lines every 5 lines with a seperator. It goes until 1000 lines

Code :

 Dim newString As String = RichTextBox1.Text.Replace(vbCr, ";").Replace(vbLf, ";")

Dim separator As Char = CChar(";")

Dim sArr As String() = newString.Split(separator)
Dim indexOfSplit As Integer = 4

Dim sFinal As String = Join(sArr.Take(indexOfSplit).ToArray, separator) & vbNewLine &
Join(sArr.Skip(indexOfSplit).ToArray, separator)

 RichTextBox2.Text = sFinal

Output : Output

Desired Output : Desired Output

The problem with my code is it does the job only for 1 line and I need it to be all lines in the string

CodePudding user response:

The RichTextBox has a Lines property that returns an array of the lines. I used a StringBuilder to build the string for RichTextBox2. The For loop increments by 4 instead of the default 1.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ParseRTB()
End Sub
Private Sub ParseRTB()
    Dim lines = RichTextBox1.Lines
    Dim sb As New StringBuilder
    For i = 0 To lines.Count - 4 Step 4
        sb.AppendLine($"{lines(i)};{lines(i   1)};{lines(i   2)};{lines(i   3)}")
    Next
    RichTextBox2.Text = sb.ToString
End Sub

CodePudding user response:

Could do this with LINQ:

RichTextBox1.Lines _
  .Select(Function(s,i) New With { .L = i\4, .S = s }) _
  .GroupBy(Function(a) a.L) _
  .Select(Function(g) string.Join(";"c, g.Select(Function(a) a.S))

This takes the lines of the rtb and projects them to a new sequence that includes a number that is the line number divided by 4 (so Howard's lines get 0, Roma's get 1 etc), then the input is grouped by that number and the grouping (a set of strings) is joined into a single string using semicolons..

  • Related