【问题标题】:How to remove a character from at string at certain position from the end?如何从字符串末尾的某个位置删除一个字符?
【发布时间】:2012-05-02 08:35:31
【问题描述】:

我有一个字符串,例如:

    Dim str as string = xxxxxxxxxxxxxxxxxxxx£xxx£xxxx**£**xxxxxxxxxx

我想从* 中删除£,该* 始终位于末尾的某个位置(例如第11 位)。整个字符串很长,总是在大小变化,从一开始就无法计数。我也不能使用Replace,其他位置可能有我不想删除的相同字符。


解决方案:

Dim rst As String = str.Remove(str.Length - 11, 1)

【问题讨论】:

标签: vb.net string trim


【解决方案1】:

编辑:哎呀,我不知道我在第一部分的想法。

第一部分的正确版本是:

str = str.Substring(0, str.Len -13) + str.Substring(str.Len-11);

String.Delete 函数也可能存在重载,它允许您使用负数来表示从字符串末尾开始的字符数——我知道 C# 等效项可以。

【讨论】:

  • 感谢 Phillip .. 你说的很对 .. 它实际上很简单,当我知道如何 .. 这里我得到了什么 .. Dim rst As String = str.Remove(str.Length - 11, 1)
  • 是的,这可能是一种更直接的方法......很好!
  • 我以为我做了元骑士!
【解决方案2】:

如果它总是从最后的第 11 个字符开始,你可以这样做......

    Dim strTargetString As String = "xxxYxxxxxxxxxx"
    Dim strTargetString2 As String = "xxxxxxxYxxxxxxxxxx"

    Dim strResult As String = Mid(strTargetString, 1, (Len(strTargetString) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
    Dim strResult2 As String = Mid(strTargetString2, 1, (Len(strTargetString2) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)

请注意,String.SubString 是一种比 Mid 更现代的方法,但我出于偏好和示例使用它。

【讨论】:

    【解决方案3】:

    这对于使用前瞻的正则表达式替换操作相当简单:

    Dim str as String = "xxxxxxxxxxxxxxxxxxxx£xxx£xxxx£xxxxxxxxxx"
    Dim str2 as String = Regex.Replace(str, "£(?=.{10}$)", String.Empty)
    

    这将针对单个字符,后跟任意十个字符,然后是字符串的结尾,并将其替换为 String.Empty 值(或者如果您愿意,也可以只是 "")。

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 2010-11-05
      • 2010-12-23
      • 1970-01-01
      • 2011-03-07
      相关资源
      最近更新 更多