【问题标题】:Trim last character from a string修剪字符串中的最后一个字符
【发布时间】:2011-04-04 03:35:56
【问题描述】:

我有一个字符串说

"Hello! world!" 

我想进行修剪或移除以取出!离开世界但不是离开你好。

【问题讨论】:

  • 也许这超出了您的要求,但我可以请您花点时间考虑一下使用我提出的正则表达式吗?
  • 在 C#8+ 中,您可以使用“范围”执行此操作:"Hello! world!"[..^1]; // yields "Hello! world"

标签: c# .net


【解决方案1】:
string s1 = "Hello! world!";
string s2 = s1.Trim('!');

【讨论】:

  • 如何使用endswith属性?这里可以用吗?
  • Trim() 的名字很糟糕。它修剪所有前导和尾随字符(复数),TrimStart() 和 TrimEnd()
【解决方案2】:

在 .NET 5 / C# 8 中:

您可以将标记为答案的代码编写为:

public static class StringExtensions
{
    public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}

但是,正如答案中提到的,这会删除最后一个字符的所有出现。如果您只想删除最后一个字符,您应该这样做:

    public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];

快速解释 C# 8 中的新内容:

^ 被称为“来自末端运算符的索引”。 .. 称为“范围运算符”。 ^1arr.length - 1 的快捷方式。您可以使用arr[1..] 获取数组第一个字符之后的所有项目,或者使用arr[..^1] 获取最后一个字符之前的所有项目。这些只是几个简单的例子。有关详细信息,请参阅https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8,“索引和范围”部分。

【讨论】:

    【解决方案3】:

    一个用于简化此的示例扩展类:-

    internal static class String
    {
        public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
        public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
        public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
    
        private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
    }
    

    用法

    "!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
    "!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
    "!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
    
    "!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
    "!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
    "!Something!".TrimEndsCharacter('!'); // Result 'Something'  (End Characters removed)
    
    "!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
    "!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
    "!!Something!!".TrimEndsCharacter('!'); // Result '!Something!'  (Only End instances removed)
    

    【讨论】:

      【解决方案4】:

      @Damian Leszczyński 的略微修改版本 - Vash 将确保仅删除特定字符。

      public static class StringExtensions
      {
          public static string TrimLastCharacter(this string str, char character)
          {
              if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
              {
                  return str;
              }
              return str.Substring(0, str.Length - 1);
          }
      }
      

      【讨论】:

        【解决方案5】:

        非常简单:

        str = str.Remove(str.Length - 1);

        【讨论】:

        • 这是我一直在寻找的,其他解决方案没有必要复杂。
        • 当问题特别要求修剪'!'时,这会删除最后一个字符,无论它是什么从最后。它也不会检查字符串是否有任何要修剪的内容,因此对于空字符串,您会得到 System.ArgumentOutOfRangeException。
        • @AntonyBooth 是的,因为问题是“从字符串中删除最后一个字符”并且没有检查义务。
        • 要求是:标题:从字符串中剪掉最后一个字符。主题:我想进行修剪或移除以取出!灭世而不灭你好。这意味着要从字符串末尾删除感叹号,而不是从字符串末尾修剪任何字符。此外,不需要说明代码示例应该可以正常工作。您的示例应如下所示: str = null != str && str.Length > 0 ? str.Remove(str.Length -1):str;也就是说,它仍然没有完全满足规定的要求。
        【解决方案6】:
        "Hello! world!".TrimEnd('!');
        

        read more

        编辑:

        我在这类问题中注意到,每个人都建议删除给定字符串的最后一个字符。但这不满足 Trim 方法的定义。

        Trim - 删除所有出现的 来自的空白字符 此实例的开始和结束。

        MSDN-Trim

        在此定义下,仅从字符串中删除最后一个字符是不好的解决方案。

        所以如果我们想“从字符串中剪掉最后一个字符”,我们应该这样做

        作为扩展方法的例子:

        public static class MyExtensions
        {
          public static string TrimLastCharacter(this String str)
          {
             if(String.IsNullOrEmpty(str)){
                return str;
             } else {
                return str.TrimEnd(str[str.Length - 1]);
             }
          }
        }
        

        注意如果你想删除所有相同值的字符,即(!!!!)上面的方法删除所有存在的'!'从字符串的末尾, 但如果你只想删除最后一个字符,你应该使用这个:

        else { return str.Remove(str.Length - 1); }
        

        【讨论】:

        • 这样会更好,只要您始终知道要从字符串末尾删除什么字符。
        • 嗨 Vash,您对我使用 RegEx 的解决方案有何看法?它满足了 Thqr 的要求,并且允许删除“!”来自任何“世界!”的字符!表达式,放置表达式的任何位置,仅在一个代码行中。
        • -1 此解决方案将删除所有相同的结尾字符!例如。它会变成“你好!!!!!!!!!”进入“Hello”,这将删除最后一个字符。
        • @Kugel,你完全正确,这就是为什么你应该再读一遍我的答案。为了解释OP不要问如何删除最后一个字符,而是如何修剪它。
        • @Vash - 你如何删除单引号 ' 使用方法 - "Hello! world!".TrimEnd('!');
        【解决方案7】:

        试试这个:

        return( (str).Remove(str.Length-1) );
        

        【讨论】:

          【解决方案8】:
          String withoutLast = yourString.Substring(0,(yourString.Length - 1));
          

          【讨论】:

          • 请确保 yourString 至少包含 1 个字符。
          • 还要确保您的字符串始终以您要删除的字符结尾 EG:“Hello!World”将以“Hello!Worl”结尾。
          【解决方案9】:
          if (yourString.Length > 1)
              withoutLast = yourString.Substring(0, yourString.Length - 1);
          

          if (yourString.Length > 1)
              withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);
          

          ...如果您想从末尾删除非空白字符。

          【讨论】:

          • 我赞成只是为了抵消反对票而没有发表评论。讨厌人们这样做。
          • 这可能是因为没有 TrimEnd() 方法,如果有它可能会使后续的 Substring(..) 调用在短字符串上失败。
          【解决方案10】:

          另一个从字符串中修剪最后一个字符的例子:

          string outputText = inputText.Remove(inputText.Length - 1, 1);
          

          您可以将其放入扩展方法中,并防止其为空字符串等。

          【讨论】:

            【解决方案11】:

            我选择使用 TrimEnd 编写扩展程序只是因为我已经在内联使用它并且对它感到满意...... 即:

            static class Extensions
            {
                    public static string RemoveLastChars(this String text, string suffix)
                    {            
                        char[] trailingChars = suffix.ToCharArray();
            
                        if (suffix == null) return text;
                        return text.TrimEnd(trailingChars);
                    }
            
            }
            

            确保使用静态类 ;P 在类中包含命名空间,用法是:

            string _ManagedLocationsOLAP = string.Empty;
            _ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");          
            

            【讨论】:

              【解决方案12】:

              你也可以使用这个:

              public static class Extensions
               {
              
                      public static string RemovePrefix(this string o, string prefix)
                      {
                          if (prefix == null) return o;
                          return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
                      }
              
                      public static string RemoveSuffix(this string o, string suffix)
                      {
                          if(suffix == null) return o;
                          return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
                      }
              
                  }
              

              【讨论】:

                【解决方案13】:

                如果您想删除“!”来自特定表达式的字符(在您的情况下为“世界”),那么您可以使用此正则表达式

                string input = "Hello! world!";
                
                string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);
                
                // result: "Hello! world"
                

                $1 特殊字符包含所有匹配的“world”表达式,用于替换原来的“world!”表达

                【讨论】:

                  【解决方案14】:
                  string s1 = "Hello! world!"
                  string s2 = s1.Substring(0, s1.Length - 1);
                  Console.WriteLine(s1);
                  Console.WriteLine(s2);
                  

                  【讨论】:

                    【解决方案15】:
                    string helloOriginal = "Hello! World!";
                    string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2011-02-13
                      • 1970-01-01
                      • 1970-01-01
                      • 2013-11-06
                      • 2017-10-16
                      • 1970-01-01
                      • 1970-01-01
                      • 2013-10-29
                      相关资源
                      最近更新 更多