0

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?

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.