如何从字符串末尾删除后缀? [英] How to remove a suffix from end of string?

查看:38
本文介绍了如何从字符串末尾删除后缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想:

  1. 检查变量并确定最后两个字符是否为Id"
  2. 如果是,请删除它们.

我可以用下面的这个来做,但是如果除了结尾之外还有一个Id"子字符串,它们会爆炸.是否有一个带多个字符参数的 RemoveFromEnd() 方法?

I can do it with this below, but them it will blow up if there is an "Id" substring other than the end. Is there a RemoveFromEnd() method that takes a number of characters argument?

 if (column.EndsWith("Id"))
 {
       //remove last 2 characters
       column = column.replace("Id", "");
 }

我看到了这个解决方案:这是这样做的:

I see this solution: which does this:

column = System.Text.RegularExpressions.Regex.Replace(column, "Id$", "");

但它说它很慢,我将在一个代码块中运行此代码,我希望它非常快,所以我想看看是否有更快的解决方案可用.

but it says it's pretty slow and I am going to be running this code inside a code block that I would like to be extremely fast so I wanted to see if a faster solution is available.

推荐答案

String.Substring 可以做到:

column = column.Substring(0, column.Length - 2);

你可以用它来滚动你自己的RemoveFromEnd:

You can use it to roll your own RemoveFromEnd:

public static string RemoveFromEnd(this string s, string suffix)
{
    if (s.EndsWith(suffix))
    {
        return s.Substring(0, s.Length - suffix.Length);
    }
    else
    {
        return s;
    }
}

这篇关于如何从字符串末尾删除后缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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