Substring a string from the end of the string

前端 未结 9 1059
别跟我提以往
别跟我提以往 2020-12-16 11:16

I need to remove two characters from the end of the string.

So:

string = \"Hello Marco !\"

must be

Hello Marco
         


        
9条回答
  •  别那么骄傲
    2020-12-16 11:46

    I will trim the end for unwanted characters:

    s = s.TrimEnd(' ', '!');
    

    To ensure it works even with more spaces. Or better if you want to ensure it works always, since the input text seems to come from the user:

    Regex r = new Regex(@"(?'purged'(\w|\s)+\w)");
    Match m = r.Match("Hello Marco   !!");
    if (m.Success)
    {
        string result = m.Groups["purged"].Value;
    }
    

    With this you are safer. A purge based on the fact the last two characters has to be removed is too weak.

提交回复
热议问题