gpt4 book ai didi

Java : Get the most similar string

转载 作者:行者123 更新时间:2023-12-01 14:13:33 26 4
gpt4 key购买 nike

需要您的另一个提示:

我有一个包含系统路径的列表:

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);
}
}
}

输出:

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\test\anything") 允许。

关于Java : Get the most similar string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com