I have an input string that looks like: /some/path/aaa/bbb/ccc/ddd
I wish to extract all possible subpaths in reverse order from this, i.e:
/some/path/aaa/bbb/ccc/ddd
/some/path/aaa/bbb/ccc
/some/path/aaa/bbb
/some/path/aaa
/some/path
/some
private static String EXAMPLE = "/some/path/aaa/bbb/ccc/ddd";
public static void main(String[] args) {
List<String> allPossibleSubpathInReverseOrder = getAllPossibleSubpathInReverseOrder(EXAMPLE);
System.out.println(allPossibleSubpathInReverseOrder);
}
private static List<String> getAllPossibleSubpathInReverseOrder(String fullPath) {
// some magic
}
Would return ["/some/path/aaa/bbb/ccc/ddd", "/some/path/aaa/bbb/ccc", "/some/path/aaa/bbb", "/some/path/aaa", "/some/path", "/some"]
I have been trying to do some kind of split()
and adding the Nth element of the split to the Nth element of the array, but I fill like there is something smarter.
private static List<String> getAllPossibleSubpathInReverseOrder(String fullPath) {
String[] split = fullPath.split("/");
List<String> result = new ArrayList<>(split.length);
int counter = split.length;
for (int i = 0; i < split.length; i++) {
}
return result;
}
Is there a way to get all combinations of paths?
1
There are several ways to adress this
You can use build the different strings from shorter prefix to longer, and add them in a list from the beginning to get your reverse order
private static List<String> getAllPossibleSubpathInReverseOrder(String fullPath) {
List<String> result = new ArrayList<>();
StringBuilder prefix = new StringBuilder();
for (String part : fullPath.replaceFirst("/", "").split("/")) {
prefix.append("/").append(part);
result.add(0, prefix.toString());
}
return result;
}