Alex
Alex

Reputation: 21

Removing the first and last character of a string C#

For an exercise on codewars I had to remove the first and last character of a string. After some fidling about I found a solution that works:

    public static string Remove_char(string s)
    {
      return s.Substring(1, s.Length - 2);   
    }

My question is why do I have to use -2 instead of -1 at the end of the return line when I only want to remove the last character?

Upvotes: 0

Views: 1560

Answers (4)

Baldie
Baldie

Reputation: 13

Because you want to return a substring from the second up to the second to last character of the initial string i.e. not the first (0th character) and not the last (length-1 character).

Upvotes: 0

mayank arora
mayank arora

Reputation: 21

the array index start from 0 and if you jump to last index then you need to s.Length-1 i.e length of array - 1. So your problem is you need to remove last character that why you added s.Length-2

Upvotes: 0

C.Evenhuis
C.Evenhuis

Reputation: 26436

Because the second parameter isn't the offset upto which you want the substring, it is the length of the desired substring.

Upvotes: 5

Christoph Sonntag
Christoph Sonntag

Reputation: 4629

The Substring counts the length starting at the first index.

So if you remove the first character the string already has s.Length-1. If you now want to remove the last character as well you need to use s.Length-2.

Upvotes: 1

Related Questions