1

我想做一些动作,直到满足以下条件之一^

  • html.IndexOf("/>")==0
  • html.IndexOf("</"+tagName+">")==0
  • html[0]=='<'

这里的 html 实际上是字符串。我试过什么 - 只需将 OR 操作应用于反转条件。但这是错误的。如何正确地做到这一点。这是我的代码:

while((html.IndexOf("/>")!=0)&&(html.IndexOf("</"+tagName+">")!=0)||(html[0]!='<'))
{
    html = html.Remove(0, 1);
}
4

2 回答 2

4

出于某种原因,您正在混合 AND 和 OR。你有

while(a && b || c) 

但你想写

while(a && b && c) 

代码应为:

while (   (html.IndexOf("/>")!=0)
        &&(html.IndexOf("</"+tagName+">")!=0)
        &&(html[0]!='<'))

我也会回应@cdhowie 的评论。使用 HTML 解析器将使您的代码更易于阅读和编写,并使其对各种输入更加健壮。

于 2013-04-01T12:11:08.403 回答
2

您的代码很难阅读。您可能需要考虑拆分各个条件以使其更易于维护:

while(true)
{
   if(html.IndexOf("/>")==0) break;             // stop the while loop if we reach the end of a tag
   if(html.IndexOf("</"+tagName+">")==0) break; // or we find the close tag
   if(html[0]=='<')) break;                     // or if we find the start of another tag

   // otherwise, do this:
   html = html.Remove(0, 1);
}
于 2013-04-01T12:13:37.177 回答