根据具体要求获取字符串的特定字符串部分

时间:2017-05-29 10:45:33

标签: vb.net

我正在开发功能,它会给我特定字符串的右侧。函数有可能根据splitted char获取返回字符串,将char保留在字符串中,并且最重要的是说返回字符串将在该char分隔符的最后一次出现之后或者在字符串中确切地说明分隔符occerence的哪个位置后返回字符串后取。任何人都可以看看并确认是否正确的方法或该代码是否包含任何问题?

请记住使用lastindex我将lastindexof设置为true并且无论splitterCharPosition是什么,反之亦然,当必须设置false splitterCharPosition时。

这是我目前要确认的代码:

 Public Function GetRightSideStringByCHar(splitterChar As String, searchingWord As String, keepCharAsWell As Boolean, lastindexof As Boolean, splitterCharPosition As Integer) As String
        Dim index As Integer
        Select Case lastindexof
            Case False
                index = GetNthIndex(searchingWord, splitterChar, splitterCharPosition)
            Case True
                index = searchingWord.LastIndexOf(splitterChar)
        End Select

        If index > 0 Then
            If keepCharAsWell Then
                searchingWord = searchingWord.Substring(0, index + splitterChar.Length)
            Else
                searchingWord = searchingWord.Substring(0, index)
            End If
        Else
            searchingWord = String.Empty
        End If
        Return searchingWord
    End Function

获取n索引的辅助函数:

 Public Function GetNthIndex(searchingWord As String, charseparator As Char, n As Integer) As Integer
        Dim count As Integer = 0
        For i As Integer = 0 To searchingWord.Length - 1
            If searchingWord(i) = charseparator Then
                count += 1
                If count = n Then
                    Return i
                End If
            End If
        Next
        Return -1
    End Function

1 个答案:

答案 0 :(得分:0)

根据你的其他删除的问题,我为你制定了这个。

它适用于您之前的所有示例。

[parameters]
str = input string
strtofind = separator string
occurance = zero-based index to start cutting (optional)
keepstringtofind = append separator to string (optional)
righttoleft = operational direction (optional)

    Public Function CutFromString(str As String, strtofind As String, Optional occurance As Integer = 0, Optional keepstrtofind As Boolean = False, Optional righttoleft As Boolean = False) As String
    Dim s As String = str
    Dim sections As List(Of String) = IIf(String.IsNullOrEmpty(str), New List(Of String), str.Split(strtofind.ToCharArray).ToList)
    If sections.Count = 1 AndAlso sections.First = str Then sections.Clear()
    If occurance < sections.Count Then
        Dim b = sections.Count - occurance
        While b > 0
            If righttoleft Then
                sections.RemoveAt(0)
            Else
                sections.RemoveAt(sections.Count - 1)
            End If
            b -= 1
        End While
        s = Join(sections.ToArray, strtofind)
        If keepstrtofind And occurance > 0 Then
            If righttoleft Then
                s = strtofind + s
            Else
                s += strtofind
            End If
        End If
    End If
    Return s
End Function