我使用以下代码拆分字符串并检索它们:
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
Dim s As String = "a,bc,def,ghij,klmno"
Dim parts As String() = s.Split(New Char() {","c})
Dim part As String
For Each part In parts
MsgBox(part(0))
Next
End Sub
但是消息框仅显示每个拆分string (a,b,d,g,k)
中的第一个字符。
我想只显示第一个字,我做错了什么?
答案 0 :(得分:5)
您的问题并不清楚,但如果您只想在字符串数组中使用第一个字,则无需循环显示
Dim firstWord = parts(0)
Console.WriteLine(firstWord) ' Should print `a` from your text sample
' or simply
Console.WriteLine(parts(0))
' and the second word is
Console.WriteLine(parts(1)) ' prints `bc`
答案 1 :(得分:2)
你已经拥有了每个部分 - 只需显示它:
For Each part In parts
MsgBox(part)
Next
part(0)
将返回字符集合中第一个字符串项。
如果你想要一个特定的索引到返回的字符串数组(按照你的comment的建议),只需直接访问它:
Dim parts As String() = s.Split(New Char() {","c})
Dim firstPart As String = parts(0)
Dim thirdPart As String = parts(2)
答案 2 :(得分:0)
您需要显示part
而不是part(0)
For Each part In parts
MsgBox(part)
Next