代码之家  ›  专栏  ›  技术社区  ›  Sphvn Frebin Francis

修剪字符串中的最后一个字符

  •  122
  • Sphvn Frebin Francis  · 技术社区  · 14 年前

    我有话要说

    "Hello! world!" 
    

    我想做一个修剪或删除了!离开世界但不是离开你好。

    14 回复  |  直到 14 年前
        1
  •  314
  •   Ahmed Masud    7 年前
    "Hello! world!".TrimEnd('!');
    

    read more

    我注意到,在这类问题中,几乎每个人都建议删除给定字符串的最后一个字符。但这并不符合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); }
    
        2
  •  68
  •   Donny V.    7 年前
    String withoutLast = yourString.Substring(0,(yourString.Length - 1));
    
        3
  •  9
  •   James    11 年前
    if (yourString.Length > 1)
        withoutLast = yourString.Substring(0, yourString.Length - 1);
    

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

    …以防要从结尾删除非空白字符。

        4
  •  7
  •   JDunkerley    14 年前
            string s1 = "Hello! world!";
            string s2 = s1.Trim('!');
    
        5
  •  6
  •   Bronek    11 年前

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

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

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

        6
  •  6
  •   Miriam Farber    7 年前

    return( (str).Remove(str.Length-1) );
    
        7
  •  5
  •   Nissim    14 年前
    string helloOriginal = "Hello! World!";
    string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
    
        8
  •  3
  •   Jonathan    14 年前
    string s1 = "Hello! world!"
    string s2 = s1.Substring(0, s1.Length - 1);
    Console.WriteLine(s1);
    Console.WriteLine(s2);
    
        9
  •  2
  •   Omu    14 年前

    你也可以用这个:

    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);
            }
    
        }
    
        10
  •  2
  •   Seyfi    6 年前

    非常简单:

    结构=str.删除( 结构长度- 1 );

        11
  •  2
  •   Antony Booth    6 年前

    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)
    
        12
  •  1
  •   Mykhailo Seniutovych    6 年前

    稍微修改了@Damian Leszczyski-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);
        }
    }
    
        13
  •  1
  •   Kody    4 年前

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

    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中新内容的快速解释:

    ^ .. 称为“范围运算符”。 ^1 是一条捷径 arr.length - 1 . 您可以使用 arr[1..] 或最后一项之前的所有项 arr[..^1] . 这些只是几个简单的例子。有关详细信息,请参阅 https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8 ,“指数和范围”部分。

        14
  •  0
  •   Brian Wells    13 年前

    即。:

    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);
            }
    
    }
    

    string _ManagedLocationsOLAP = string.Empty;
    _ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");          
    
        15
  •  -5
  •   Marcello Faga    14 年前

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