gpt4 book ai didi

java - 如何从字符串中找到匹配的单词以及百分比值?

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

我有主弦。

String main = "hi how are you? i am fine.";

然后是一些字符串..

String string1 = "hi people what is the need................ how to ................... do the needful.................................. and you can only need the change......................................... in the fine situation................................................. to do the task................... i am alright............... are you okay?";

(可能在100字左右)

String string2 = "how to do...................i don't know the need......... what i am supposed to do......................fine i am.......... okay..";

(可能在100字左右)

String string3 = "some string again................";

(可能在100字左右)

String string4 = "some string again................";

(可能在100字左右)

现在,我要做的是,ma​​in字符串中有7个单词..

正如您所看到的,所有这 7 个单词都出现在 string1 中。4 个单词出现在 string2 中......然后继续......

所以,现在 string1 的百分比值为 100%..对于 string2,百分比值为 57.xx%.. 依此类推..

所以,我想以编程方式获取这些百分比值..

到目前为止我尝试过的是,

String perc;

String[] q1 = str1.split(" ");
String[] q2 = main.split(" ");

for (String temp1: q1) {
for (String temp2: q2) {
if(temp1.equals(temp2)) {
// Some code here
}
}
}

现在我不知道从哪里开始?

最佳答案

这里是如何做到的:

String main = "hi how are you? i am fine.";
// Extract all the words whose length is > 1 and remove duplicates
Set<String> mainWords = new HashSet<>();
for (String s : main.split("\\W")) {
if (s.length() > 1) {
mainWords.add(s);
}
}
String string1 = "hi people what is the need................ how to ................... do the needful.................................. and you can only need the change......................................... in the fine situation................................................. to do the task................... i am alright............... are you okay?";

Set<String> mainWordsToFind = new HashSet<>(mainWords);
// Iterate over all the words and remove the word from the list to find
for (String word : string1.split("\\W")) {
if (word.length() > 1) {
mainWordsToFind.remove(word);
}
}

// Print the percent of word found
System.out.println((double) (mainWords.size() - mainWordsToFind.size()) / mainWords.size());

输出:

1.0

关于java - 如何从字符串中找到匹配的单词以及百分比值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37209689/

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