2014-09-02 123 views
-3

我需要實現以下目標:動態字符串分割

Dim lstrSource as String = "Hello-Hi" 

要獲得「喜」的來源,我們將適用,lstrSource.Split("-")(1)

但是,我的源字符串每次都會改變,並且分割操作指令也會被用戶輸入。

所以,我試圖達到這樣的東西。

Dim lstrSpiltInstn as String = "Split("-")(1)" 

lstrSource.lstrSplitInstn =>這就需要返回「嗨」

,纔有可能還是有什麼其他方式來實現這一目標。

+1

'lstrSource.Split(「 - 」)(0)''將返回'Hello' **不**''嗨'。 – 2014-09-02 08:19:42

+0

分隔符和數組索引已經是變量。你只需要存儲他們兩個。 – 2014-09-02 13:10:39

回答

2

「嗨」是第二個標記,而不是第一個標記。除此之外,參數應該是分隔符和索引,而不是方法本身。

所以,你可以使用這個方法:

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)