Substring a string from the end of the string

Viewed 131181

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

So:

string = "Hello Marco !"

must be

Hello Marco

How can I do it?

9 Answers

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

str[^2..]

This is equivalent to

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

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.

Related