我想扫描一个html页面并计算“.”的次数。 (句号)出现。这里我有一些读取 html 的代码,并打印出所需的输出。
我本来想修改这段代码,但鉴于这是一个简单的问题,也许我们不需要修改它;相反,我们可以直接编写一个新程序。
这是我读取网页html的代码(其中很多应该是不必要的代码):
import edu.duke.*;
public class URLFinder {
public StorageResource findURLs(String url) {
URLResource page = new URLResource(url);
String source = page.asString();
StorageResource store = new StorageResource();
int start = 0;
while (true) {
int index = source.indexOf("href=", start);
if (index == -1) {
break;
}
int firstQuote = index+6; // after href="
int endQuote = source.indexOf("\"", firstQuote);
String sub = source.substring(firstQuote, endQuote);
if (sub.contains(".")) {
store.add(sub);
}
start = endQuote + 1;
}
return store;
}
public void testURL() {
StorageResource s1 = findURLs("http://www.dukelearntoprogram.com/course2/data/newyorktimes.html");
//StorageResource s2 = findURLs("http://www.doctorswithoutborders.org");
for (String link : s1.data()) {
System.out.println(link);
}
System.out.println("size = " + s1.size());
//System.out.println("size = " + s2.size());
}
}
最佳答案
一种方法是使用 indexOf
方法:
int index = -1;
int count = 0;
String source = ...;
while((index = source.indexOf(".", ++index) != -1)
count++
正如@TJCrowder 所指出的,您可能需要让某些脚本执行。如果是这种情况,请引用this上一个SO问题。
关于java - 如何统计 "."在网页中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34506152/