Trim last character from a string

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

    Slightly modified version of @Damian Leszczyński - Vash that will make sure that only a specific character will be removed.

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

提交回复
热议问题