Luke Villanueva
Luke Villanueva

Reputation: 2070

Using substring on string manipluation

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!

Upvotes: 0

Views: 84

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

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

Upvotes: 1

brent
brent

Reputation: 1488

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.

Upvotes: 0

Related Questions