Substring a string from the end of the string

前端 未结 9 1070
别跟我提以往
别跟我提以往 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:56

    C# 8 introduced indices and ranges which allow you to write

    str[^2..]
    

    This is equivalent to

    str.Substring(str.Length - 2, str.Length)
    

    In fact, this is almost exactly what the compiler will generate, so there's no overhead.

    Note that you will get an ArgumentOutOfRangeException if the range isn't within the string.

提交回复
热议问题