Java tutorial
//package com.java2s; //License from project: Open Source License import java.util.Collection; public class Main { /** * Compute the common root xpath for all provided xpaths * @param xpaths list of xpaths * @return common root of provided list */ public static String commonRoot(Collection<String> xpaths) { String commonPath = ""; String[][] folders = new String[xpaths.size()][]; int c = 0; for (String xpath : xpaths) { folders[c++] = xpath.split("/"); //split on file separator } for (int j = 0; j < folders[0].length; j++) { String thisFolder = folders[0][j]; //grab the next folder name in the first path boolean allMatched = true; //assume all have matched in case there are no more paths for (int i = 1; i < folders.length && allMatched; i++) { //look at the other paths if (folders[i].length < j) { //if there is no folder here allMatched = false; //no match break; //stop looking because we've gone as far as we can } //otherwise allMatched &= folders[i][j].equals(thisFolder); //check if it matched } if (allMatched) { //if they all matched this folder name commonPath += thisFolder + "/"; //add it to the answer } else {//otherwise break;//stop looking } } return commonPath; } }