一个可能的解决方案:
循环遍历路径列表,将它们拆分为反斜杠字符,然后遍历结果数组的每个值。查看它与参考路径的值相等的时间,并相应地给它们打分。我的例子有点粗糙,但你可以相应地调整它。
public class PathScore {
public String Path;
public int Score;
}
public class Systempaths {
public static void main(String[] args) {
new Systempaths();
}
public Systempaths() {
String[] paths = new String[5];
paths[0] = "C:\\System\\local\\something\\anything";
paths[1] = "C:\\System\\local\\anywhere\\somewhere";
paths[2] = "C:\\System\\local";
paths[3] = "C:\\System\\";
paths[4] = "C:\\something\\somewhere";
String ref = "C:\\System\\local\\test\\anything";
String[] reference = ref.split("\\\\");
List<PathScore> scores = new ArrayList<>();
for (String s : paths) {
String[] exploded = s.split("\\\\");
PathScore current = new PathScore();
current.Path = s;
for (int i = 0; i < exploded.length; i++) {
if (exploded[i].equals(reference[i])) {
current.Score = i + 1;
} else {
// Punishment for paths that exceed the reference path (1)
current.Score = i - 1;
break;
}
}
scores.add(current);
}
for (PathScore ps : scores) {
System.out.printf("%s:\t%d\n", ps.Path, ps.Score);
}
}
}
输出:
C:\System\local\something\anything: 2
C:\System\local\anywhere\somewhere: 2
C:\System\local: 3
C:\System\: 2
C:\something\somewhere: 0
C:\System\local\something\anything
(1):我对过于具体且超出参考路径 ( "C:\System\local\test\anything"
) 允许的路径(如 )添加了一个小惩罚。