Reputation: 688
I am extracting a substring from a string that comes from a word file. But I am getting an error of index out of range
even if the starting and ending index of substring is less then the length of the string.
for(int i=0;i<y.Length-1;i++)
{
if (Regex.IsMatch(y[i], @"^[A]"))
{
NumberOfWords= y[i].Split(' ').Length;
if (NumberOfWords > 5)
{
int le = y[i].Length;
int indA = y[i].IndexOf("A");
int indB = y[i].IndexOf("B");
int indC = y[i].IndexOf("C");
int indD = y[i].IndexOf("D");
//if (indD > 1 && indC > 1)
// breakop2 = breakop2 + '\n' + '\n' + y[i].Substring(indC, indD);
if (indC > 1 && indB > 1)
breakop1 = breakop1 + '\n' + y[i].Substring(indB, indC);
if (indB > 1)
sr = y[i].Substring(indA, indB);
else
sr = y[i];
breakop = breakop +'\n'+'\n'+ sr;
Acount++;
//textBox1.Text = s[i];
check1 = check1 + '\n' + '\n' + y[i];
//i++;
}
}
}
Upvotes: 3
Views: 150
Reputation: 17721
The String.Substring method takes a starting index and a length. You are passing in two indices.
Upvotes: 9
Reputation: 1500595
String.Substring(int, int)
doesn't take a start index and an end index (as it does in Java); it takes a start index and a length. So perhaps you want:
sr = y[i].Substring(indA, indB - indA);
But you should also check that indB
is greater than indA
. (You need to work out how you want this to behave if B
comes before A
, basically.)
You'd also need to apply the same behaviour for the Substring(indB, indC)
.
Upvotes: 11