Surbhi
Surbhi

Reputation: 4078

Why getting ArgumentOutOfRangeException in finding substring

Length of clines[i] is 69 I have initialized index = 50

Code:

string substr = clines[i].Substring(index, clines[i].Length);

Now I want substring from index 50 to 69 But I am getting below exception

ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length

why I am getting this exception?

Upvotes: 1

Views: 776

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

The immediate cause of the error in your code is that index + clines[i].Length must not exceeds actual string's length which is clines[i].Length and that's why you're going to have the error for every non-zero index.

Try dropping the last argument (if you want to get the substring starting from the index and up to the end):

 string substr = clines[i].Substring(index);

Edit: A (wordy) alternative with two arguments is

 string substr = clines[i].Substring(index, clines[i].Length - index);

Please, notice that the last argument is the length of the substring, not of the original one.

Upvotes: 6

Glenn Ferrie
Glenn Ferrie

Reputation: 10410

In C#, the second argument represents the length of the segment you want to take, not the index to which you want the segment to extend to.

Also, if you want the right part of the string -- you can just leave off the second parameter.

clines[i].Substring(50, 19);

Upvotes: 1

Related Questions