比较路径长度

时间:2016-03-22 07:49:51

标签: java path

我试图只保留最近的路径,我使代码计数出现了斜线,我得到了结果:

html/body/div/header/div/div/a/span = 7
html/body/div/div/div/div/div/div/div/div/div/h2 = 11
html/body/div/div/div/table/tbody/tr/td/ul/li/a = 11
html/body/div/div/div/table/tbody/tr/td/ul/li/a/h1 = 12
html/body/div/div/div/div/table/tbody/tr/td/a/span = 11
html/body/div/div/div/div/table/tbody/tr/td/a/span/h1 = 12
html/body/div/div/div/div/table/tbody/tr/td/a/a/span/h1 = 13

我希望最后只保留彼此接近的路径,它必须返回这样的东西:

html/body/div/div/div/div/div/div/div/div/div/h2 = 11
html/body/div/div/div/table/tbody/tr/td/ul/li/a = 11
html/body/div/div/div/table/tbody/tr/td/ul/li/a/h1 = 12
html/body/div/div/div/div/table/tbody/tr/td/a/span = 11
html/body/div/div/div/div/table/tbody/tr/td/a/span/h1 = 12
html/body/div/div/div/div/table/tbody/tr/td/a/a/span/h1 = 13 

我从这个Java代码开始:

ArrayList<String> list_input = new ArrayList();
        list_input.add("");

        list_input.add("html/body/div/header/div/div/a/span");
        list_input.add("html/body/div/div/div/div/div/div/div/div/div/h2");
        list_input.add("html/body/div/div/div/table/tbody/tr/td/ul/li/a");
        list_input.add("html/body/div/div/div/table/tbody/tr/td/ul/li/a/h1");
        list_input.add("html/body/div/div/div/div/table/tbody/tr/td/a/span");
        list_input.add("html/body/div/div/div/div/table/tbody/tr/td/a/span/h1");
        list_input.add("html/body/div/div/div/div/table/tbody/tr/td/a/a/span/h1");

        for (int i = 0; i < list_input.size(); i++) {
            String line = (String) list_input.get(i);

            int count_nodes = line.length() - line.replace("/", "").length();
            System.out.println(line + " = " + count_nodes);

        }

有人会帮我实现这个结果吗?

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

String[] temp = line.split("/");
int count = temp.length;

编辑:

String line = (String)list_input.get(0);
int min = line.split("/").length;

for (int i = 1; i < list_input.size(); i++) {
    String line = (String)list_input.get(i);

    int count = line.split("/").length;
    if (count < min)
        min = count;
}

答案 1 :(得分:0)

for(String str: list_input){
            System.out.println(str.split("/").length);
}