0

I would like to display index together with the string. This is what I have tried.

 Dim strA As String = "Bell-in-hospital"
 Dim i As Integer = 1

 Dim arrayList() As String = strA.Split({" - "}, StringSplitOptions.RemoveEmptyEntries)

For index As Integer = 0 To arrayList.Length - 1
    MsgBox("location:" & arrayList(index) & arrayList.ToString())
    index += 1
Next

Now, I'm stuck at For each on how can I display the index together with content. Thanks for the help.

6
  • 1
    Did you tried For index As Integer = 0 To arrayList.Length - 1? Commented Sep 4, 2019 at 7:44
  • 1
    You have to use a for, not a for each Commented Sep 4, 2019 at 7:44
  • Ive edited my code, is that correct? @Fabio Commented Sep 4, 2019 at 7:57
  • why? @Babbillumpa Commented Sep 4, 2019 at 7:57
  • Look at Fabio's answer and you will see. However Eugene solution is also an option. Commented Sep 4, 2019 at 8:00

2 Answers 2

3

When you need to loop array with corresponding index use For...Next Statement (Visual Basic)

For index As Integer = 0 To arrayList.Length - 1
    MsgBox($"index: {index}, value: {arrayList(index)}")
Next
Sign up to request clarification or add additional context in comments.

Comments

1
        Dim strA As String = "Bell-in-hospital"
        'index starts from 0 in arrays
        Dim i As Integer = 0

        Dim arrayList() As String = strA.Split({"-"}, StringSplitOptions.RemoveEmptyEntries)
        For Each test As String In arrayList
        MsgBox("Index: "& i &" String:  "& test)
        'increase index
        i = i + 1
        Next

5 Comments

Variable i is redundant, For Next loop will increment index automatically
@Fabio i is not redundant since we are using For Each Not For Next . Thank you..
why is i redundant? @Fabio
Does that mean i will be redundant if we use For Next? @EugeneOgongo
@lara, it will be redundant when you are using For Next, Use For Each loop when you don't need index and want just to enumerate all collection items. Every loop has own purpose and using it correctly will save your and others time, especially others time when they will read your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.