4

我正在使用以下代码拆分字符串并检索它们:

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

但消息框仅显示每个 splitted 中的第一个字符string (a,b,d,g,k)

我只想显示第一个单词,我做错了什么?

4

3 回答 3

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`
于 2013-02-01T20:48:55.757 回答
2

您已经拥有每个部分 - 只需显示它:

For Each part In parts
  MsgBox(part)
Next

part(0)将返回字符集合中作为字符串的第一项。

如果您想要返回的字符串数组中的特定索引(如您的评论所建议的那样),只需直接访问它:

Dim parts As String() = s.Split(New Char() {","c})
Dim firstPart As String = parts(0)
Dim thirdPart As String = parts(2)
于 2013-02-01T20:46:30.723 回答
0

你需要显示partpart(0)

For Each part In parts

     MsgBox(part)
    Next
于 2013-02-01T20:47:42.357 回答