[VB.NET]將字串分割,並產生字串陣列

  • 38089
  • 0
  • 2010-08-02

字串切割,但字串中的空白數量不一時所做的處理

 

1. 問題描述

假設有一個字串     Dim MyString = "09/02/04     4:00p   21.9 21.9  21.8 69     15.9            3.6 NE        2.15 6.3 "

中間間格不止一個空白,如何將字串切割且不產生空白陣列

 

2. 方法

感謝 AllenKuo 提供很好的解決辦法,可參考 http://www.allenkuo.com/userfiles/share/2009q1/2009-2-5_13-22-28.png,或 AllenKuo 的留言

 

在 String.Split 方法 (Char[], StringSplitOptions) 中,可以透過參數 StringSplitOptions 來對空字串做處理

StringSplitOptions 列舉

image

 

程式碼

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' === 字串切割 ===
        Dim MyString = "09/02/04     4:00p   21.9 21.9  21.8 69     15.9            3.6 NE        2.15 6.3 "
        Dim charSeparators() As Char = {" "c}
        Dim strResult() = MyString.Trim().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)

        ' === 顯示 ===
        For i As Integer = 0 To strResult.Length - 1
            Me.TextBox1.Text += strResult(i) + Environment.NewLine
        Next
    End Sub
End Class

 

3. 執行結果

image

 

4. 下載

[VB]Split.rar