I apologize for the vague topic title, but the actual topic title would be very long.

Is it possible that after you find a string, backup until you find a specific character and copy it?

For example, I am looking for "bread". The text is milk8andbread. Would it be possible to start at bread, back up until eight, and just copy "andbread"?

Please feel free to ask any questions.

Thank you,

Resentful

Member Avatar for Unhnd_Exception
Dim s As String = "milk8andbread"
        Dim index As Integer = s.IndexOf("bread")

        If index <> -1 Then
            'shows andbread
            If index > 3 AndAlso index + 3 < s.Length Then
                MsgBox(s.Substring(index - 3, 8)) '8 length of bread + 3
            End If

            'shows bread
            MsgBox(s.Substring(index, 5)) '5 length of bread
        End If

Will that work in all situations, or just with the one mentioned? I am looking for one that will work in all situations.

Member Avatar for Unhnd_Exception

If you want to back up 3 each time. and the length of the search string is 5

I'll give you a permanent solution if you state exactly what you want.

Back up 3 each time?

Member Avatar for Unhnd_Exception

This will work everytime.

returns an empty string on bad input.

Dim s As String = SubString("milkandbread", "bread", 8)
MsgBox(s)


Private Function SubString(ByVal OriginalString As String, ByVal SearchString As String, ByVal TotalLength As Integer) As String

        If String.IsNullOrEmpty(OriginalString) Then Return String.Empty
        If String.IsNullOrEmpty(SearchString) Then Return String.Empty
        If SearchString.Length > TotalLength Then Return String.Empty

        Dim index As Integer = OriginalString.IndexOf(SearchString)

        If index = -1 Then Return String.Empty

        Dim difference As Integer = TotalLength - SearchString.Length

        If index - difference < 0 Then Return String.Empty

        Return OriginalString.Substring(index - difference, TotalLength)

    End Function
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.