Split String by last occurence

2019-07-09 07:47发布

问题:

I have a String like this:

www.myserver.net/Files/Pictures/2014/MyImage.jpg

And I want to split it, so I get the Substring after the last occurence of /. Which means I like to get MyImage.jpg I tried it like this:

  MsgBox(URL.Substring(URL.LastIndexOf("/"), URL.Length - 1))

But that wont work. Can someone help me out how to do this in VB.Net? C# is also okay, after I've understood the logic, I can convert it myself.

回答1:

Use System.IO.Path.GetFileName instead:

Dim path = "www.myserver.net/Files/Pictures/2014/MyImage.jpg"
Dim filename = System.IO.Path.GetFileName(path) ' MyImage.jpg

For the sake of completeness, you could also use String.Split or String.Substring:

filename = path.Split("/"c).Last()
' or 
Dim lastIndex = path.LastIndexOf("/")
If lastIndex >= 0 Then
    fileName = path.Substring(lastIndex + 1)
End If

But it is more error-prone and less readable.