VB.NET中的动态字符串拆分

时间:2014-09-02 08:16:38

标签: vb.net string random

我需要实现以下目标:

Dim lstrSource as String = "Hello-Hi"

获得"嗨"在来源中,我们将申请lstrSource.Split("-")(1)

但是,我的源字符串每次都会改变,而分割操作指令也会进入用户。

所以,我正在努力实现这样的目标。

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

lstrSource.lstrSplitInstn =>这需要返回"嗨"

是否可能或有其他方法可以实现这一目标。

1 个答案:

答案 0 :(得分: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)