2020年4月22日 星期三

VBNET 將字串分割,並產生字串陣列

VBNET 將字串分割,並產生字串陣列
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

-------
另外 微軟又有調整新的用法
Strings.Split(String, String, Int32, CompareMethod) 方法

Dim testString As String = "apple    pear banana  "
Dim testArray() As String = Split(testString)
' testArray holds {"apple", "", "", "", "pear", "banana", "", ""}
Dim lastNonEmpty As Integer = -1
For i As Integer = 0 To testArray.Length - 1
    If testArray(i) <> "" Then
        lastNonEmpty += 1
        testArray(lastNonEmpty) = testArray(i)
    End If
Next
ReDim Preserve testArray(lastNonEmpty)
' testArray now holds {"apple", "pear", "banana"}

沒有留言:

張貼留言