0

我正在尝试找到一种将路径(原始 URL)轻松拆分为两部分的方法:例如:/search/criteria/newyork/list

我想填充一个包含第三个斜杠之前的所有内容的字符串,在这种情况下:“/search/criteria” 我还想将第二部分放入一个字符串:“newyork/list”

4

4 回答 4

1

试试这个:

Dim sAux() As String = sURL.Split("/"c)
Dim sResult As String = ""

If sAux.Length > 3 Then
    For i As Integer = 2 to sAux.Length - 1
        sResult &= sAux(i) & "/"
    Next
End If

或这个:

Dim sAux As New List(Of String)(sURL.Split("/"c))
sAux.RemoveRange(0,2)    

sResult = String.Join("/", sAux.ToArray())
于 2013-03-14T16:22:00.807 回答
1

您可以使用IndexOf查找第三个斜线(假设第一个字符始终是第一个斜线,并且字符串中至少有三个斜线):

Dim index3 = url.IndexOf("/"c, url.IndexOf("/"c, 1) + 1)

然后,您可以使用Substring该斜线之前和之后的部分:

Dim path As String = url.Substring(0, index3)
Dim resource As String = url.Substring(index3 + 1)
于 2013-03-14T16:28:05.157 回答
0
        Dim ar As String()
        Dim str1 As String
        Dim str2 As String
        Dim a As Integer
        Dim splitPosition = 3
        Dim urlToSplit = "/search/criteria/newyork/list"
        ar = urlToSplit.Split("/"c)

        If UBound(ar) < splitPosition Then
            ' there are 3 or less slashes. do what you want here, error or just exit
        Else
            For a = 0 To splitPosition - 1
                If Not String.IsNullOrEmpty(ar(a)) Then str1 += ar(a) + "/"
            Next
            For a = splitPosition To UBound(ar)
                If Not String.IsNullOrEmpty(ar(a)) Then str2 += ar(a) + "/"
            Next
        End If

str1将包含/search/criteria/ str2将包含newyork/list/

此代码将处理任意数量的/组合,并且不应该为格式错误的 Url 出错

于 2013-03-14T16:33:18.633 回答
0

如果您的字符串始终采用相同的格式并且具有相同数量的元素(在拆分数组中),您可以使用String.Format方法 as;

Dim arr() As String =  "/search/criteria/newyork/list".Split("/"c)
Dim str1 As String = String.Format("/{1}/{2}", arr) '/search/criteria
Dim str2 As String = String.Format("{3}/{4}", arr) 'newyork/list
于 2013-03-14T16:53:58.820 回答