「嗨」是第二個標記,而不是第一個標記。除此之外,參數應該是分隔符和索引,而不是方法本身。
所以,你可以使用這個方法:
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