views:

170

answers:

5

Test string:

the%20matrix%20

How can I delete the last three chars? Using this code gives me an out of index exception:

y = y.Substring(y.Length - 4, y.Length - 1);
+1  A: 

You need to check that the string is at least 3 characters long first.

if (y.Length > 2)
{
}

As others have said the version of Substring you want parameters are startIndex and length.

Though what do you want to do with 1 or 2 character strings?

ChrisF
+1  A: 

You want y.Substring(0, y.Length-4)

Chris Marisic
+2  A: 

If you want to delete the last three characters, you need the first parameter of your Substring method to be zero.

dalovega
that answer is wrong, too - it is the right problem, but he will get everything but the last character ...
tanascius
+3  A: 

As dalovega said, you need the first parameter of Substring to be 0 and the second Length - 3. As an alternative:

if(y.Length >= 3)
{
    y = y.Remove(y.Length - 3)
}
Philip Wallace
since he said 'any string' this seems to work fine, dont need to do the UrlDecoding.
SomeMiscGuy
Good point - well spotted!
Philip Wallace
+13  A: 

Seems this isn't your REAL problem; if you want to remove that "%20", you should use:

string test = "the%20matrix%20";
string clean = HttpUtility.UrlDecode(test);

if (clean.Length > 2) // if you still want to strip last chars...
    clean = clean.Substring(0, clean.Length - 3);
Rubens Farias
+1 For teaching me something I didn't know (UrlDecode) and also giving a solution to what is most likely the real issue here.
Philip Wallace