我正在创建 C# winforms 应用程序,它必须在文件中查找所有出现的字符串,裁剪中间的文本,然后进行一些处理。
文本文件格式如下:
---- Key_String ----
text to crop 1
---- Key_String ----
text to crop 2
---- Key_String ----
text to crop 3
基本上我是从该文件中裁剪“text1”、“text2”、“text3”。
下面是执行上述操作的代码:
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"
}
它适用于我的一些文件,但在某些情况下 - 我收到以下错误:
Index and length must refer to a location within the string. Parameter name: length
这很奇怪,因为我正在裁剪的子字符串位于主字符串内部,而不是像您猜测的那样位于外部。我可以用“try-catch”输出来证明这一点:
Index 1: 3211
Index 2: 4557
Max index (length - 1): 5869
如您所见 - 我没有裁剪位于索引范围之外的内容,所以有什么问题吗?
附言我用谷歌搜索了解决方案,但每种情况下的基本思想都是——“错误的索引”。在我的例子中——索引在范围内。好吧,至少我是这么认为的。
编辑
与此类似的东西应该可以解决问题:
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));
}
最佳答案
Substring
不采用两个索引。它需要一个索引和一个长度。也许,你想要
indd2 - indd1
作为第二个参数(并检查该表达式是否存在差一错误)。
关于c# - 解决异常 "out of range"错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12019230/