【问题标题】:Trim a string from a specific character on从特定字符修剪字符串
【发布时间】:2013-12-31 12:06:13
【问题描述】:

我有一个文本框,它的文本属性是这样的路径,例如:

/users/me/whatever

我想要的是删除最后一个“文件夹”并拥有这个:

/users/me

我已经尝试过使用修剪和拆分功能,但现在我没有达到我想要的效果。

编辑:

Private Sub btn_Back_Click(sender As Object, e As EventArgs) Handles btn_Back.Click

    If Not (txt_Path.Text = "/") Then
        txt_Path.Text = ... ?
    End If

End Sub

有人可以帮忙吗?谢谢

【问题讨论】:

  • Split on /, string.LastIndexOf.. 正则表达式有很多方法可以做到这一点。没有代码所以不知道你为什么在挣扎。
  • 刚刚在我的帖子中插入了代码

标签: vb.net string trim


【解决方案1】:

很简单:

Dim str = txt_Path.Text
Dim i = str.LastIndexOf("/")
If i <> -1 then
   txt_Path.Text = str.Substring(0, i)
End if

【讨论】:

  • 谢谢,不完全是我想要的,但现在必须这样做
  • @chiapa 你在找什么?
  • 哦,别误会我的意思,结果正是我需要的,但我希望找到一些字符串函数,它可以删除特定字符上的所有内容,就像我的问题的标题一样!
  • @chiapa 我认为没有内置这样的函数,但是如果您需要在其他地方重用它,您可以使用上面的代码轻松创建自己的字符串类扩展函数。跨度>
  • 是的,我知道。再次感谢
【解决方案2】:

你可以试试Path.GetDirectoryName

txt_Path.Text = Path.GetDirectoryName(txt_Path.Text)

【讨论】:

    【解决方案3】:

    你也可以使用regular expression解析这个:

    Dim dir As String
    
    ' this may not work as expected if a user ends the directory with as slash, try it to see and then decide if that is ok or not?
    ' this regex pattern keeps everything except "everything that follows the last slash"
    dir = Regex.Replace("/users/me/whatever", "^(.*)\/.*[^\/]$", "$1")
    Console.WriteLine(dir)
    

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 2015-07-25
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多