“嗨”是第二个标记,而不是第一个标记。除此之外,参数应该是分隔符和索引,而不是方法本身。
所以,你可以使用这个方法:
Public Shared Function SplitByGetAt(input As String, delimiter As String, index As Int32, options As StringSplitOptions) As String
If input Is Nothing Then Throw New ArgumentNullException("input")
If delimiter Is Nothing Then Throw New ArgumentNullException("delimiter")
If delimiter.Length = 0 Then Throw New ArgumentException("Delimiter must be specified", "delimiter")
If index < 0 Then Throw New ArgumentException("Index must be equal or greater than 0", "index")
Dim tokens = input.Split({delimiter}, options)
If index >= tokens.Length Then Return Nothing
Return tokens(index)
End Function
用法:
Dim lstrSource as String = "Hello-Hi"
Dim result As String = SplitByGetAt(lstrSource, "-", 1, StringSplitOptions.None)
' Result: Hi
如果你想成为一个扩展方法:
Public Module MyExtensions
<Extension()>
Public Function SplitByGetAt(input As String, delimiter As String, index As Int32, options As StringSplitOptions) As String
If input Is Nothing Then Throw New ArgumentNullException("input")
If delimiter Is Nothing Then Throw New ArgumentNullException("delimiter")
If delimiter.Length = 0 Then Throw New ArgumentException("Delimiter must be specified", "delimiter")
If index < 0 Then Throw New ArgumentException("Index must be greater than 0", "index")
Dim tokens = input.Split({delimiter}, options)
If index >= tokens.Length Then Return Nothing
Return tokens(index)
End Function
End Module
现在,您可以使用它这样:
lstrSource.SplitByGetAt("-", 1, StringSplitOptions.None)
'lstrSource.Split(“ - ”)(0)''将返回'Hello' **不**''嗨'。 – 2014-09-02 08:19:42
分隔符和数组索引已经是变量。你只需要存储他们两个。 – 2014-09-02 13:10:39