how to split delimited space and trim in vb.net

50 Views Asked by At

I'm Trying to split delimited space and trim in vb.net.

Please Guide Me

Thanks

Module Module1
Sub Main()
Dim s As String = "     5010    2024-03-18 06:59:10 1   0   0   0"
Dim words As String() = s.Split(CType(vbTab, Char()))
 For Each word As String In words
            Console.WriteLine("WORD: {0}", word)
        Next
        Console.Read()
    End Sub

End Module

output from above code

WORD:      5010
WORD: 2024-03-18 06:59:10
WORD: 1
WORD: 0
WORD: 0
WORD: 0

desired output


WORD: 5010
WORD: 2024-03-18
WORD: 06:59:10
WORD: 1
WORD: 0
WORD: 0
WORD: 0
2

There are 2 best solutions below

0
user23548857 On

according to recommendations from @Blackcat

and based on this link https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-8.0#system-string-split(system-char())

Module Module1

    Sub Main()
Dim s As String = "     5010    2024-03-18 06:59:10 1   0   0   0"
Dim separators As Char() = New Char() {" "c, Char.Parse(vbTab)}
        Dim words As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each word As String In words
            Console.WriteLine("WORD: {0}", word)
        Next
        Console.Read()
    End Sub

End Module


Output Result

WORD: 5010
WORD: 2024-03-18
WORD: 06:59:10
WORD: 1
WORD: 0
WORD: 0
WORD: 0
0
dbasnett On

One more. When I copied and pasted original code the tabs were scrubbed, or they were scrubbed when posted.

    Dim s As String = " 5010    2024-03-18  06:59:10    1   0   0   0"
    Dim splts() As Char = {ControlChars.Tab, " "c}
    Dim words() As String = (From foo In s.Split(splts, StringSplitOptions.RemoveEmptyEntries) Select foo.Trim).ToArray
    For Each word As String In words
        Console.WriteLine("WORD: {0}", word)
    Next
    Console.Read()