Trim last character from a string

后端 未结 14 1372
谎友^
谎友^ 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:33

    I took the path of writing an extension using the TrimEnd just because I was already using it inline and was happy with it... i.e.:

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

    Make sure you include the namespace in your classes using the static class ;P and usage is:

    string _ManagedLocationsOLAP = string.Empty;
    _ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");          
    
    0 讨论(0)
  • 2020-11-30 00:34

    The another example of trimming last character from a string:

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

    You can put it into an extension method and prevent it from null string, etc.

    0 讨论(0)
  • 2020-11-30 00:35

    If you want to remove the '!' character from a specific expression("world" in your case), then you can use this regular expression

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

    the $1 special character contains all the matching "world" expressions, and it is used to replace the original "world!" expression

    0 讨论(0)
  • 2020-11-30 00:36

    you could also use this:

    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);
            }
    
        }
    
    0 讨论(0)
  • 2020-11-30 00:40
    string helloOriginal = "Hello! World!";
    string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
    
    0 讨论(0)
  • 2020-11-30 00:42
    if (yourString.Length > 1)
        withoutLast = yourString.Substring(0, yourString.Length - 1);
    

    or

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

    ...in case you want to remove a non-whitespace character from the end.

    0 讨论(0)
提交回复
热议问题