Java:获取最相似的字符串
需要您的另一个提示: 我有一个包含系统路径的列表:Java:获取最相似的字符串,java,Java,需要您的另一个提示: 我有一个包含系统路径的列表: 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\loca
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\
那怎么办呢 由于您有一个预定义的系统路径列表,现在您有了一个参考路径,您需要从列表中找出最相似的系统路径,因此我的假设是参考路径和系统路径列表中的每个项目之间的匹配。基于正则表达式的比较会更容易 一个可能的解决方案: 循环遍历路径列表,在反斜杠字符上拆分路径,然后循环遍历结果数组的每个值。查看它与引用路径的值相等的时间,并相应地给它们打分。我的例子有点粗糙,但你可以相应地加以调整
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);
}
}
}
(1) :
我为路径(如C:\System\local\something\anything
)添加了一个小小的惩罚,这些路径太过具体,并且超出了参考路径(“C:\System\local\test\anything”
)允许的范围。您的示例实际上表明,答案是给定路径开始时最长的系统路径。这可按如下方式计算:
String[] systemPaths = ...
String path = ...
String bestMatch = null;
for (String candidate : systemPaths) {
if (path.startsWith(candidate) &&
(bestMatch == null || bestMatch.length() < candidate.length())) {
bestMatch = candidate;
}
}
String[]系统路径=。。。
字符串路径=。。。
字符串bestMatch=null;
for(字符串候选:系统路径){
if(路径开始与(候选)和
(bestMatch==null | | bestMatch.length()
这假设系统路径都以文件分隔符结尾,并且您希望区分大小写进行匹配。如果没有,调整应该很明显。为每个条目计算一个分数。应根据什么评估分数?分析你自己的例子。另外,我可能会给你一些想法一个可能的重复感谢,删除斜线和得分计数器为我做到了!
String[] systemPaths = ...
String path = ...
String bestMatch = null;
for (String candidate : systemPaths) {
if (path.startsWith(candidate) &&
(bestMatch == null || bestMatch.length() < candidate.length())) {
bestMatch = candidate;
}
}