Trim last character from a string

后端 未结 14 1373
谎友^
谎友^ 2020-11-29 23:59

I have a string say

\"Hello! world!\" 

I want to do a trim or a remove to take out the ! off world but not off Hello.

相关标签:
14条回答
  • 2020-11-30 00:43

    Try this:

    return( (str).Remove(str.Length-1) );
    
    0 讨论(0)
  • 2020-11-30 00:44

    An example Extension class to simplify this: -

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

    Usage

    "!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)
    
    0 讨论(0)
  • 2020-11-30 00:45

    Very easy and simple:

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

    0 讨论(0)
  • 2020-11-30 00:47
    String withoutLast = yourString.Substring(0,(yourString.Length - 1));
    
    0 讨论(0)
  • 2020-11-30 00:47
            string s1 = "Hello! world!";
            string s2 = s1.Trim('!');
    
    0 讨论(0)
  • 2020-11-30 00:55
    string s1 = "Hello! world!"
    string s2 = s1.Substring(0, s1.Length - 1);
    Console.WriteLine(s1);
    Console.WriteLine(s2);
    
    0 讨论(0)
提交回复
热议问题