当前位置: 动力学知识库 > 问答 > 编程问答 >

vb.net - Textbox Hell - Delete 3 Lines, Skip 1, Repeat

问题描述:

I have a textbox that reads like so:

Line 1

Line 2

Line 3

**Line 4**

Line 1

Line 2

Line 3

**Line 4**

(repeats...)

How can I use VB to loop through the textbox, deleting Lines 1, 2, and 3, skipping the fourth, and repeat? Or, rather, record every fourth line into a new textarea?

Thanks! I'm SO lost!

网友答案:

I'd probably get the contents, split on the newline character to create an array of strings (one string per line), then loop through the array outputting only the ones i wanted.

网友答案:

If this is VB6 then bear in mind that the variable length String type is a reference type meaning that operations will involve taking a deep copy i.e. concatenation is expensive.

  Dim lines() As String
  lines = VBA.Split(TextBox1.Text, vbCrLf)

  Dim counter As Long
  For counter = 3 To UBound(lines) Step 4
    lines(counter) = Chr$(22)
  Next

  TextBox1.Text = _
      Replace$( _
          Replace$( _
              VBA.Join(lines, vbCrLf), _
          vbCrLf & Chr$(22), vbNullString), _
      Chr$(22) & vbCrLf, vbNullString, 1)
网友答案:

This is code for the previous answer.

Private Function EveryFourthLine(ByVal input As String) As String
        Dim newtxt As String = ""
        Dim oldtxt As String() = input.Split(vbCrLf)

        For i As Integer = 1 To oldtxt.Count
            If i Mod 4 = 0 Then
                newtxt = newtxt & oldtxt(i - 1)
                If i <> oldtxt.Count Then
                    'add a vbcrlf to all but the last line
                    newtxt = newtxt & vbCrLf
                End If
            End If
        Next

        Return newtxt
End Function
网友答案:

If this is VB.Net and you are using a Textbox - you don't need to split anything yourself. You can just access the .Lines property. You'll get back an array of strings

You certainly can loop through the rows, like others have shown; but another approach is to use LINQ to do that work for you.

        txtBox1.Lines = (From curLine In txtBox1.Lines _
                         Where Array.IndexOf(txtBox1.Lines, curLine) Mod 4 = 3).ToArray

What you are saying here is that you want the Lines in the textbox to be equal to all of the lines that are already in the text box - as long as the index of that particular line, divided by 4 has a remainder of three.

That sounds complicated when you type it out like that, but really, all it's going to do is give you every fourth line, and set that back into the textbox.

分享给朋友:
您可能感兴趣的文章:
随机阅读: