Reputation: 279
I am taking a line from a file only if that file doen't have a specific pattern.. and i want to take from that line the last 3 chars... my code is:
while (!line.Contains(pattern))
{
String num = line.Substring((line.Length - 3), (line.Length - 2));
System.Console.WriteLine(num);
}
but i get an error..
Index and length must refer to a location within the string. Parameter name: length
why i get that? i am starting the new string 3 chars before the end of the line and i stop 2 chars before.. :\
Upvotes: 5
Views: 2790
Reputation: 981
The problem is that you try to get more characters then your array have.
Extensions are best for problems like this one ;) Mine have some dirty name but everyone know what it would do - this is exception safe substring:
public static string SubstringNoLongerThenSource(this string source, int startIndex, int maxLength)
{
return source.Substring(startIndex, Math.Min(source.Length - startIndex, maxLength));
}
So in your exact problem it should be like that:
String num = line.SubstringNoLongerThenSource((line.Length - 3), 3);
System.Console.WriteLine(num);
So num will have max 3 letters if the string you provide to function have enough letters :)
Upvotes: 1
Reputation: 10410
This is happening because the last parameter of Substring() should be the length of the string to extract.
In your case it should be 3
, and not line.Length - 2
The first parameter should also be:
line.Length - 3
Upvotes: -1
Reputation: 26940
This is dangerous. What if the length of the line is < 3? You should probably check this otherwise you will get an exception.
In addition you should use the substring method as depicted here :
String num = line.Substring((line.Length - 3), 3);
Upvotes: 1
Reputation: 1651
Second argument of Substring
is how many chars it have to take starting from first argument. It should just look like that:
String num = line.Substring(line.Length - 3, 3);
Upvotes: 2
Reputation: 91716
Substring takes an offset and then a number of characters to return:
http://msdn.microsoft.com/en-us/library/aa904308%28v=VS.71%29.aspx
So:
String num = line.Substring((line.Length - 3), 3);
This of course assumes that line.Length > 3. You could check with:
String num = (line.Length < 3) ? line : line.Substring((line.Length - 3), 3);
Upvotes: 9