Reputation: 4078
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
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
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