需要你提供另一个提示:
我有一个包含系统路径的列表:
C:\System\local\something\anything
C:\System\local\anywhere\somewhere
C:\System\local\
C:\System\
C:\something\somewhere
我的参考路径是:
C:\System\local\test\anything\
现在我正在寻找最相似的系统路径,结果应该是
Result from the list :
C:\System\local\
那该怎么办?
答案 0 :(得分:1)
可能的解决方案:
循环遍历路径列表,将它们拆分为反斜杠字符,然后循环到结果数组的每个值。查看它等于参考路径值的长度,并相应地给它们一个分数。我的例子有点粗糙,但你可以相应调整它。
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
(1):
我为路径(如C:\System\local\something\anything
)添加了一个小惩罚,这些路径过于具体,比参考路径("C:\System\local\test\anything"
)允许的更远。
答案 1 :(得分:0)
由于你有一个预定义的系统路径列表,现在你有一个参考路径,你需要从列表中找出最相似的系统路径,我的参考路径和参考路径之间的匹配系统路径列表中的每个项目。基于正则表达式的比较会更容易。
答案 2 :(得分:0)
那么你的例子是实际,表明答案是给定路径开始的最长系统路径。这可以按如下方式计算:
String[] systemPaths = ...
String path = ...
String bestMatch = null;
for (String candidate : systemPaths) {
if (path.startsWith(candidate) &&
(bestMatch == null || bestMatch.length() < candidate.length())) {
bestMatch = candidate;
}
}
这假设系统路径都以文件分隔符结束,并且您希望敏感地执行匹配大小写。如果没有,调整应该是显而易见的。