【问题标题】:Split String by last occurence按最后一次出现拆分字符串
【发布时间】:2014-03-25 09:41:34
【问题描述】:

我有一个这样的字符串:

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

我想拆分它,所以我在最后一次出现 / 之后得到子字符串。 这意味着我喜欢获取 MyImage.jpg 我试过这样:

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

但这行不通。有人可以帮助我如何在 VB.Net 中执行此操作吗? C#也可以,理解了逻辑后,我就可以自己转换了。

【问题讨论】:

    标签: vb.net string split lastindexof


    【解决方案1】:

    改用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

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

    但它更容易出错且可读性较差。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 2014-01-12
      • 2022-01-25
      • 2013-12-28
      • 2019-01-06
      • 2021-12-02
      • 2014-01-21
      • 2017-04-29
      相关资源
      最近更新 更多