How to split a string on multiple multi‑character delimiters (and keep them) in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module Module1

    Private Function IsDelimChar(c As Char, delims As String()) As Boolean
        For Each d In delims
            If d.Length > 0 AndAlso d(0) = c Then
                Return True
            End If
        Next
        Return False
    End Function

    Public Function SplitKeepMultiDelims(s As String, delims As String()) As List(Of String)
        Dim result As New List(Of String)()
        Dim i As Integer = 0

        While i < s.Length
            Dim c As Char = s(i)

            If IsDelimChar(c, delims) Then
                ' Count repeated delimiter characters
                Dim start As Integer = i
                While i < s.Length AndAlso s(i) = c
                    i += 1
                End While
                result.Add(s.Substring(start, i - start))

            Else
                ' Collect normal text until next delimiter run
                Dim start As Integer = i
                While i < s.Length AndAlso Not IsDelimChar(s(i), delims)
                    i += 1
                End While
                result.Add(s.Substring(start, i - start))
            End If
        End While

        Return result
    End Function

    Sub Main()
        Dim s As String = "aa==bbb---cccc++++ddddd"
        Dim delims() As String = {"=", "-", "+"}

        Dim parts = SplitKeepMultiDelims(s, delims)

        For Each p In parts
            Console.Write("[" & p & "] ")
        Next
    End Sub

End Module



' run:
'
' [aa] [==] [bbb] [---] [cccc] [++++] [ddddd] 
'

 



answered Mar 10 by avibootz

Related questions

...