我正在尝试计算 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
。这不是计数的好理由"div"
不过,因为您会拾取较长单词的部分内容(例如 Division
或 Divorce
)。
如果您想要更好的计数,您可以使用简单的正则表达式来进行计数:
"[</]div[ />]"
此正则表达式将匹配 div
前面是 <
或/
,后跟一个空格,/
,或>
:
Pattern countRx = Pattern.compile("[</]div[ />]", Pattern.CASE_INSENSITIVE);
Matcher m = countRx.matcher(sHtml);
int count = 0;
while (m.find()) {
count++;
}
System.out.println(count);
关于java - JAVA中忽略大小写计算子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26749560/