Fatir Rizky
Fatir Rizky

Reputation: 67

Substring Method in VB.Net

I have Textboxes Lines:

{ LstScan = 1,100, DrwR2 = 0000000043 }
{ LstScan = 2,200, DrwR2 = 0000000041 }
{ LstScan = 3,300, DrwR2 = 0000000037 }

I should display:

1,100
2,200
3,300

this is a code that I can't bring to a working stage.

 Dim data As String = TextBox1.Lines(0)
    ' Part 1: get the index of a separator with IndexOf.
    Dim separator As String = "{ LstScan ="
    Dim separatorIndex = data.IndexOf(separator)
    ' Part 2: see if separator exists.
    ' ... Get the following part with Substring.
    If separatorIndex >= 0 Then
        Dim value As String = data.Substring(separatorIndex + separator.Length)
        TextBox2.AppendText(vbCrLf & value)
    End If

Display as follows:

1,100, DrwR2 = 0000000043 }

Upvotes: 0

Views: 6935

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

This should work:

Function ParseLine(input As String) As String
    Const startKey As String = "LstScan = "
    Const stopKey  As String = ", "

    Dim startIndex As String = input.IndexOf(startKey)
    Dim length As String = input.IndexOf(stopKey) - startIndex
    Return input.SubString(startIndex, length)
End Function

TextBox2.Text = String.Join(vbCrLf, TextBox1.Lines.Select(AddressOf ParseLine))

If I wanted, I could turn that entire thing into a single (messy) line... but this is more readable. If I'm not confident every line in the textbox will match that format, I can also insert a Where() just before the Select().

Upvotes: 1

Caius Jard
Caius Jard

Reputation: 74710

Your problem is you're using the version of substring that takes from the start index to the end of the string:

"hello world".Substring(3) 'take from 4th character to end of string

lo world

Use the version of substring that takes another number for the length to cut:

"hello world".Substring(3, 5) 'take 5 chars starting from 4th char

lo wo

If your string will vary in length that needs extracting you'll have to run another search (for example, searching for the first occurrence of , after the start character, and subtracting the start index from the newly found index)


Actually, I'd probably use Split for this, because it's clean and easy to read:

 Dim data As String = TextBox1.Lines(0)
 Dim arr = data.Split() 
 Dim thing = arr(3)

thing now contains 1,100, and you can use TrimEnd(","c) to remove the final comma

 thing = thing.TrimEnd(","c)

You can reduce it to a one-liner:

TextBox1.Lines(0).Split()(3).TrimEnd(","c)

Upvotes: 1

Related Questions