0

I have a string that has a string length of 66

Then I display it, using this one:

string.Substring(0, 20);
string.Substring(21, 40);
string.Substring(41, 60); --Error here
string.Substring(61, string.Length)

Why do I get an error saying that. Index and length must refer to a location within the string. Parameter name: length

Any ideas? Thanks!

2
  • thatshould be 66. My bad Commented Oct 12, 2013 at 13:14
  • 1
    The second parameter should be the length. So, if you start from 41 and go up to 60 length, you will get an exception, Since your total string length should be at least 41+60 Commented Oct 12, 2013 at 13:16

2 Answers 2

1

well,

first argument for substring is the start position

second argument for substring is the length, not the end position

41 + 60 = 101 => it's a little bit more than 66.

you should use

string.Substring(0, 20);
string.Substring(21, 20);
string.Substring(41, 20); 
string.Substring(61, 5);

Edit :

const int Length = 20;
var str = "myString";
var i = 0;
var list = new List<string>();
do {
  list.Add(str.Substring(i *Length, Math.Min(str.Length - (i*Length), Length)));
  i++;
}while (str.Length > i*Length);
Sign up to request clarification or add additional context in comments.

4 Comments

I want to divide a strinng by 20 characters. No matter how long it is. So a long string will break down into series of string lines
So I should not use subtring if I want to divide it by atleast 20 characters
@ljpv14 see edit, you'll have the idea (use Math.Min to avoid exception in substring)
@Raphaël Althaus code will do exactly what your after, for strings of any length..
0

The second parameter in C#'s substring method is length, in the last two examples there are not that many characters left to take a substring of.

Comments

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.