Home > Net >  Count lines between two values in RichTextBox
Count lines between two values in RichTextBox

Time:12-15

I want to count the lines between 2 values in a Richtextbox, depending on if its easier if they are the same values or not i can edit the data which will be shown in the Richtextbox.

The Richtextbox will look like this:

--BEGIN1
ABC
DEF
GHI
KLM
--END1
--BEGIN2
NOP
QRS
TUV
--END2

and so on... i want to count the lines between the begin/end

I experimented with different ways but i cant get it to count between those values.

Idea behind it is to tell me if the number of lines between the values is correct or if theres a line missing which will add a warning to the text but i can figure that out my self, help with counting the lines between 2 values would be appreciated.

TiA

CodePudding user response:

First get the lines from the RichTextBox through the Lines property. The loop through the lines and remember the index of the block start. When you encounter a block end, you can easily calculate the number of lines between the start and the current index.

Dim lines As String() = richTextBox1.Lines
Dim start As Integer

For i As Integer = 0 To lines.Length - 1
    Dim line As String = lines(i)
    Dim blockNumber As String = ""
    If line.StartsWith("--BEGIN") Then
        blockNumber = line.Substring(7)
        start = i
    ElseIf line.StartsWith("--END") Then
        Console.WriteLine($"Block # = {blockNumber}, Number of lines = {i - start - 1}")
    End If
Next

For your example this prints in a console test:

Block # = 1, Number of lines = 4
Block # = 2, Number of lines = 3

You will have to replace the Console.WriteLine by whatever you want to do with the result.

  • Related