2014-09-02 83 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)