按最后一次出现拆分字符串 [英] Split String by last occurence

查看:33
本文介绍了按最后一次出现拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

I have a String like this:

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

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

我想拆分它,所以我在最后一次出现/后得到子字符串.这意味着我喜欢得到 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))

但这行不通.有人可以帮助我如何在 VB.Net 中做到这一点吗?C#也可以,明白逻辑后,我可以自己转换了.

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.

推荐答案

使用 System.IO.Path.GetFileName:

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

为了完整起见,您还可以使用 String.SplitString.Substring:

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.

这篇关于按最后一次出现拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆