【发布时间】:2014-11-05 04:09:23
【问题描述】:
我正在尝试计算我的 html 文件中 div 标签的出现次数。当我搜索 div 时,我得到 2,而对于 DIV,我得到 1650。所以理想情况下,当我使用 sHtml.toUpperCase(),然后搜索 DIV 时,我应该得到 1652。但我得到了 1656。这里可能出了什么问题?
/********* Counting occurences of div **************/
String findString = "DIV";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = sHtml.indexOf(findString, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findString.length();
}
}
System.out.println("Count of div = " + count);
【问题讨论】:
-
给出奇数的特定测试用例会让某人准确地知道发生了什么。这很可能是下面的一般答案之一。
-
这不会真正起作用,因为您的方法也会选择像
<!-- DIV for main -->和类似的 cmets。你真的应该使用 HTML 解析器,这是唯一的方法。 -
哦,是的。说得通。谢谢。我也是这方面的新手,我可以在 eclipse 中使用什么样的 HTML 解析器?
-
@tanvi 这对 SO 来说是题外话,但我相信 jsoup 是一个流行的解析器。
-
@tanvi Google says there's lots.