我将例程从C ++移植到C#并且很难理解端口失败的原因:
我有一个字符串数组,其中包含我想要删除的内容。
string[] aryLines = File.ReadAllLines(mstrFilename);
该数组包含以下内容:
aryLines = new[]
{
"<?xml version=\"1.0\" encoding=\"utf-8\"?>",
"<!--",
"",
" File:\t\tuif.xml, User Interface",
" Notes:\tThis file contains the application layout and includes",
"\t\tfor other files defining the application look and functionality.",
"",
" Node:\t\tuif, Root container node",
" Attributes:\tid\t\t: Unique node identifier",
"\t\tcameras\t\t: Initial camera set-up",
" \t\tcolor_bg\t: Application background colour:",
"\t\t\t\t\tAlpha, Red, Green, Blue",
"\t\theight\t\t: Height of the application container",
"\t\twidth\t\t: Width of the appplication container\t\t",
"",
" Node:\t\tinclude, Includes another XML file",
" Attributes:\tname\t\t: Encoded path to XML file to include",
"",
" History:\t2017/09/11 Created by Simon Platten",
"// -->"
};
我有一个方法可以删除评论,找到第一次出现的<!--
和匹配的-->
,然后它将删除其中的所有内容。问题是虽然它找到<!--
但它找不到-->
但我不明白为什么。
private static readonly string msrostrCmtClose = "-->";
private static readonly string msrostrCmtOpen = "<!--";
int intOpen = 0;
while((intOpen = Array.IndexOf(aryLines, msrostrCmtOpen, intOpen)) >= 0)
{
//Opening marker located, look for closing marker
int intClose = Array.IndexOf(aryLines, msrostrCmtClose, intOpen);
if ( intClose < intOpen )
{
//Shouldn't get here!
continue;
}
Console.WriteLine(intOpen);
}
上面的例程没有完成,但是在调试器中观察intClose总是-1,为什么?
答案 0 :(得分:0)
这里的问题是Array.IndexOf
会将每个元素与您要查找的内容进行比较,但您正在寻找的内容实际上并不在数组中。数组中的内容是// -->
,而不只是-->
。
你可以做的是创建一个这样的简单函数:
private int IndexOfInArray(string[] array, string elemToFind, int startIndex = 0)
{
for (int i = startIndex; i < array.Length; i++)
{
if (array[i].Contains(elemToFind))
return i;
}
return -1;
}
然后像这样使用它:
int intOpen = 0;
while((intOpen = IndexOfInArray(aryLines, msrostrCmtOpen, intOpen)) >= 0 )
{
//Opening marker located, look for closing marker
int intClose = IndexOfInArray(aryLines, msrostrCmtClose, intOpen);
if (intClose < intOpen)
{
//Shouldn't get here!
continue;
}
Console.WriteLine(intOpen);
}
您可能必须将intOpen
设置为intClose
或仅intOpen++
才能永远无法获得相同的结果。
答案 1 :(得分:0)
我现在已经解决了这个问题,感谢评论中的建议,新的解析器看起来像这样:
string strXML = File.ReadAllText(mstrFilename);
int intOpen = 0;
while( (intOpen = strXML.IndexOf(msrostrCmtOpen, intOpen)) >= 0 ) {
//Opening marker located, look for closing marker
int intClose = strXML.IndexOf(msrostrCmtClose, intOpen);
if ( intClose < intOpen ) {
//Shouldn't get here!
continue;
}
Console.WriteLine(intOpen);
}