Reputation: 733
I'm trying to find a way to easily split a path (Raw URL) in two portions: For example: /search/criteria/newyork/list
I would like to populate a string that would contain everything before third slash, in this case: "/search/criteria" I also want to get the second portion into a string: "newyork/list"
Upvotes: 0
Views: 521
Reputation: 33809
If your string is always in the same format and has same number of elements (in splited array), you could use String.Format
method 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
Upvotes: 0
Reputation: 2213
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
will contain /search/criteria/
str2
will contain newyork/list/
This code will handle any number of /
combinations and should not error out for a badly formed Url
Upvotes: 0
Reputation: 700322
You can use IndexOf
to find the third slash (assuming that the first character is always the first slash, and that there are at least three slashes in the string):
Dim index3 = url.IndexOf("/"c, url.IndexOf("/"c, 1) + 1)
Then you can use Substring
to get the parts before and after that slash:
Dim path As String = url.Substring(0, index3)
Dim resource As String = url.Substring(index3 + 1)
Upvotes: 1
Reputation: 9888
Try this:
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
Or this:
Dim sAux As New List(Of String)(sURL.Split("/"c))
sAux.RemoveRange(0,2)
sResult = String.Join("/", sAux.ToArray())
Upvotes: 1