The index and length must refer to the location inside the string error in the substring

I have a line like this: 2899 8761 014 00:00:00 06/03/13 09:35 G918884770707 . I have to take the substring G918884770707 from this string. I know the beginning of the substring, so I take the end of the substring as the length of the entire string as follows:

  No = line.Substring(Start,End); 

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

This causes an error:

The index and length must refer to the location inside the string error in the substring

How to resolve this?

+4
string substring c # string-length
source share
1 answer

You misunderstood the Substring parameters - they do not start or end (as in Java) re start and length.

So you want:

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

From the docs:

STARTINDEX Options
Type: System.Int32
The starting position of the zero substring character in this instance.

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

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

Always, always read the documentation - especially if you get an exception that you do not understand.

+12
source share

All Articles