string 在逗号上拆分字符串并打印结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14654707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:47:42  来源:igfitidea点击:

Splitting a string on comma and printing the results

vb.netstringsplit

提问by Samuel Medhat

I am using the following code to split a string and retrieve them:

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

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

But the message box shows only the first character in each splitted string (a,b,d,g,k).

但是消息框只显示每个拆分的第一个字符string (a,b,d,g,k)

I want to show only the first word, what am I doing wrong?

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

回答by Steve

It is not clear from your question, but if you want only the first wordin your array of strings then no need to loop over it

从您的问题中不清楚,但是如果您只想要字符串数组中的第一个单词,则无需遍历它

 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`

回答by Oded

You already have each part - just display it:

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

For Each part In parts
  MsgBox(part)
Next

part(0)will return the first item in the character collection that is a string.

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

If you want a specific index into the returned string array (as suggested by your comment), just access it directly:

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

Dim parts As String() = s.Split(New Char() {","c})
Dim firstPart As String = parts(0)
Dim thirdPart As String = parts(2)

回答by bonCodigo

You need to show partnot part(0)

你需要显示partpart(0)

For Each part In parts

     MsgBox(part)
    Next