VisualBasic version
Code to find sub-string, if found, return the trailing part - the remainder of the string immediately behind (trailing the end) of the found sub-string.
jp2code's answer fitted my purpose in an elegant fashion. In addition to examples, the author also indicated the code has been well tried and tested over time. VisualBasic equivalent of his/her code:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Function TextFollowing(txt As String, value As String) As String
If Not String.IsNullOrEmpty(txt) AndAlso Not String.IsNullOrEmpty(value) Then
Dim index As Integer = txt.IndexOf(value)
If -1 < index Then
Dim start As Integer = index + value.Length
If start <= txt.Length Then
Return txt.Substring(start)
End If
End If
End If
Return Nothing
End Function
End Module
The code has been tested using VS Community 2017.
Usage example
Dim exampleText As String = "C-sharp to VisualBasic"
Dim afterCSharp = exampleText.TextFollowing("to")
'afterCSharp = " VisualBasic"
The extension method TextFollowing() is now avaliable to String objects.
- Line 1:
exampleText is String and therefore our extension method is available
- Line 2:
exampleText.TextFollowing() uses the extension method
Complementary method
It may be useful to have the complementary method - obtain the preceding portion of the string. The complementary extension methods are written and placed together in one combined code module:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Function TextFollowing(txt As String, value As String) As String
If Not String.IsNullOrEmpty(txt) AndAlso Not String.IsNullOrEmpty(value) Then
Dim index As Integer = txt.IndexOf(value)
If -1 < index Then
Dim start As Integer = index + value.Length
If start <= txt.Length Then
Return txt.Substring(start)
End If
End If
End If
Return Nothing
End Function
<Extension()>
Public Function TextPreceding(txt As String, value As String) As String
If Not String.IsNullOrEmpty(txt) AndAlso Not String.IsNullOrEmpty(value) Then
Dim index As Integer = txt.IndexOf(value)
If -1 < index Then
Return txt.Substring(0, index)
End If
End If
Return Nothing
End Function
End Module
Usage example
Dim exampleText As String = "C-sharp to VisualBasic"
Dim beforeVisualBasic = exampleText.TextPreceding("to")
'beforeVisualBasic = "C-sharp "
In my use case, it is necessary to check if LargeString.Contains(SmallString) prior to using these extension methods. For faster code execution this could have been combined with the extension methods presented above which I did not. This is because no slow-ness is experienced therefore the preference is on code reusability.
Substring()call is failing is because you're asking fortxtPriceLimit.Text.Lengthcharacters starting fromindex. Meaning the entire length of your string would have to beindex + txtPriceLimit.Text.Length.