VisualBasic 版本
查找子字符串的代码,如果找到,则返回尾随部分 - 紧跟在找到的子字符串后面(尾随结尾)的字符串的其余部分。
jp2code 的回答以一种优雅的方式符合我的目的。除了示例之外,作者还表示该代码已经过一段时间的很好的尝试和测试。 VisualBasic 相当于他/她的代码:
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
代码已使用 VS Community 2017 进行了测试。
使用示例
Dim exampleText As String = "C-sharp to VisualBasic"
Dim afterCSharp = exampleText.TextFollowing("to")
'afterCSharp = " VisualBasic"
扩展方法TextFollowing() 现在可用于String 对象。
- 第 1 行:
exampleText 是 String,因此我们的扩展方法可用
- 第 2 行:
exampleText.TextFollowing() 使用扩展方法
互补法
使用补充方法可能很有用 - 获取字符串的前面部分。互补的扩展方法被编写并放在一个组合代码模块中:
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
使用示例
Dim exampleText As String = "C-sharp to VisualBasic"
Dim beforeVisualBasic = exampleText.TextPreceding("to")
'beforeVisualBasic = "C-sharp "
在我的用例中,有必要在使用这些扩展方法之前检查LargeString.Contains(SmallString)。为了更快地执行代码,这可以与上面介绍的扩展方法相结合,而我没有。这是因为没有遇到缓慢的情况,因此优先考虑代码的可重用性。