Index and length must refer to a location within the string error in substring

shubham Hegdey picture shubham Hegdey · Sep 28, 2014 · Viewed 18.9k times · Source

I have a string like this: 2899 8761 014 00:00:00 06/03/13 09:35 G918884770707. I have to take the substring G918884770707 from this given string. I know the start of the substring so I'm taking the end of the substring as the length of the whole string like this:

 No = line.Substring(Start,End);

Here the value of Start is 39 and the length of the main string is 52 so this is the value for End.

This causes the error:

Index and length must refer to a location within the string error in substring

How do I resolve this?

Answer

Jon Skeet picture Jon Skeet · Sep 28, 2014

You've misunderstood the parameters to Substring - they aren't start and end (as they are in Java), they're start and length.

So you want:

No = line.Substring(Start, End - Start);

From the docs:

Parameters startIndex
Type: System.Int32
The zero-based starting character position of a substring in this instance.

length
Type: System.Int32
The number of characters in the substring.

Return Value
Type: System.String
A string that is equivalent to the substring of length length that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance and length is zero.

Always, always read the documentation - particularly if you're getting an exception that you don't understand.