Search code examples
.netvb.netsplitstring-function

Split a string into parts


I am trying to split a string into parts but can't figure it out!

My main point is from a string

"hello bye see you" 

read from "bye" to "you"

I tried

 Dim qnew() As String = tnew.Split(" ")

But I got stuck on other parts of the code, I would really like some help. Sorry if I'm not the best at explaining things, at least I tried my best :/


Solution

  • I assume that your expected output is bye see you.If I understood correctly then following methods can be used to get the desired output:

    In this string splits into an array(splits()) with delimiter " " and find index of bye (j)and you(k) in the array then using a for loop to get strings in the array between bye and you.

    Function GETSTRINGBETWEEN(ByVal start As String, ByVal parent As String, ByVal [end] As String)
            Dim output As String = ""
            Dim splits() As String = parent.Split(" ")
            Dim i As Integer
            Dim j As Integer = Array.IndexOf(splits, start)
            Dim k As Integer = Array.IndexOf(splits, [end])
            For i = j To k
                If output = String.Empty Then
                    output = splits(i)
                Else
                    output = output & " " & splits(i)
                End If
            Next
            Return output
        End Function
    

    Usage:

    Dim val As String
    val = GETSTRINGBETWEEN("bye", "hello bye see you", "you")
    'val="bye see you"
    

    Function GET_STRING_BETWEEN(ByVal start As String, ByVal parent As String, ByVal [end] As String)
            Dim output As String
            output = parent.Substring(parent.IndexOf(start) _
                                                    , (parent.IndexOf([end]) _
                                                       - parent.IndexOf(start)) _
                                                       ).Replace(start, "").Replace([end], "")
            output = start & output & [end]
            Return output
        End Function
    

    Usage:

    Dim val As String
    val = GET_STRING_BETWEEN("bye", "hello bye see you", "you")
    'val="bye see you"