user6096423
user6096423

Reputation: 141

Find String line number concurrently with locating the line in VB

I successfully use this code to get the text from the line I am looking for:

Dim lines = all_prices.Split({vbCrLf}, StringSplitOptions.None)
Dim match = lines.FirstOrDefault(Function(x) x.EndsWith("1820160831"))

The sample data is:

10|100|1820160830
20|200|1820160831
30|300|1820160901

The current result is:

20|200|1820160831

What I want is to append to the line found the line number where it is found, eg:

20|200|1820160831-2

EDIT

I tried this solution:

indexOfText = Array.FindIndex(lines, Function(str) str.IndexOf("1820160831", StringComparison.InvariantCultureIgnoreCase) >= 0)

but the result is always -1

Upvotes: 0

Views: 710

Answers (3)

Daniel Anderson
Daniel Anderson

Reputation: 275

First, I would check to see if your Split() function is working properly by getting the total number of lines it returns:

MsgBox(lines.Length)

I don't think it's working though, because that's not the right way to use Split with a line feed. Try this:

Dim lines As String() = all_prices.Split(new String() {Environment.NewLine},
                                   StringSplitOptions.None)

That should give you the array you need to search against.

EDIT

To get the line number, you could try this:

Dim lineNo as Integer
lineNo = -1  // Set to a value that reflects no match if there is none
For i As Integer = 0 To lines.GetUpperBound(0)
  If lines(i).EndsWith("1820160831") = true then
      lineNo = i
      match += "-" & (i + 1)
      Exit For
  End If
Next
MsgBox(lineNo)

Upvotes: 1

soohoonigan
soohoonigan

Reputation: 2360

Give this a try, returns the index of the first match and appends the index to the string...

Dim all_prices As String = "10|100|1820160830" & vbCrLf & "20|200|1820160831" & vbCrLf & "30|300|1820160901"
Dim lines() As String = all_prices.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
Dim i As Integer = Enumerable.Range(0, lines.Count).Where(Function(x) lines(x).EndsWith("1820160831")).First
lines(i) = lines(i) & "-" & i.ToString 

"(i+1).ToString" on the last line instead of "i" if you want the line-number rather than the index

Upvotes: 2

Je Shaps
Je Shaps

Reputation: 21

Dim lines = all_prices.Split({vbCrLf}, StringSplitOptions.None)
Dim match = lines.FirstOrDefault(Function(x) x.EndsWith("1820160831"))

For i As Integer = 0 To lines.GetUpperBound(0)
Dim matches As Boolean = lines(i).EndsWith("1820160831")
    If matches Then
        match += "-" & (i + 1)
        Exit For
    End If
Next

Upvotes: 2

Related Questions