solving unusual “out of range” error behavior
-
27-06-2021 - |
Question
I'm creating C# winforms app which has to find all occurences of a string within a file, crop the text in between, then do some processing.
The text file has following format:
---- Key_String ----
text to crop 1
---- Key_String ----
text to crop 2
---- Key_String ----
text to crop 3
Basically I'm croping "text1", "text2", "text3" from that file.
And here is the code to do the mentioned action:
string contents = "";
MatchCollection matches;
using (StreamReader reader = File.OpenText(filepath))
{
contents = reader.ReadToEnd();
matches = Regex.Matches(contents, "Key_String");
}
int totalmatchcount = matches.Count;
for (int i = 0; i < totalmatchcount; i++ )
{
int indd1 = matches[i].Index;
int indd2 = 0;
string sub_content = "";
if (i != totalmatchcount - 1)
{
indd2 = matches[i+1].Index;
try
{
sub_content = contents.Substring(indd1, indd2); // error here
}
catch
{
MessageBox.Show("Index 1: " + indd1 + "\n" +
"Index 2: " + indd2 + "\n" +
"Max index (length - 1): " + (contents.Length - 1)
);
}
}
else { sub_content = contents.Substring(indd1); }
// do some stuff with "sub_content"
}
It works great for some of my files, however in some cases - I'm getting following error:
Index and length must refer to a location within the string. Parameter name: length
It is very strange, because the substring that I'm cropping is located INSIDE the main string, not outside as you have guessed. I can prove it with "try-catch" output:
Index 1: 3211
Index 2: 4557
Max index (length - 1): 5869
As you can see - I'm not cropping something that is located outside the index range, so what's the problem?
P.S. I've googled solutions but the basic idea in every case is - "wrong index". In my case - index is "inside" the range. Well, at least I think so. Any help would be appreciated.
EDIT:
Something similar to this should solve the problem:
public string SubstringFix(string original, int start, int end)
{
int endindex = 0;
if (end < original.Length)
{
endindex = end;
}
else
{
endindex = original.Length - 1;
}
return original.Substring(start, (end - start));
}
Solution
Substring
does not take two indices. It takes one index and a length. Probably, you want
indd2 - indd1
as the second parameter (and check that expression for off-by-one errors).
OTHER TIPS
With what you have this is what you are getting
3211+4557 = 7768
and that is greater than the length of the string.
This is how substring works
substring(startindex, length)
Length of string should not be less than startIndex + length