1

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?

1
  • 2
    Substring is not (from, to). It's (from, howmany) Reading the actual documentation could have answered you, rather than creating this question. Commented Dec 30, 2016 at 7:26

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

string substr = clines[i].Substring(index); This worked. But I have a question in substring() we don't have to pass last index? Why?
@Surabhi Pandey: You can well put it as string substr = clines[i].Substring(index, clines[i].Length - index); but why bother with the last argument when you have a sutable method's overload? Since .Net provides Substrting(index) method which means "starting from index and up to the end", why don't we use it?
@DmitryBychenko Thanks for correcting. Removed my comment.
@DmitryBychenko- Thank you :)
1

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);

1 Comment

yeah I got it now. I am new to c# . Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.