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

时间:2016-05-13 12:07:44

标签: java android string percentage string-matching

我有主弦。

  

String main =“你好吗?我很好。”

然后几个字符串..

  

String string1 =“ hi 人们有什么需要................ 如何到   ................... 做需要的事情............................ ......   并且只能需要   改变.........................................在罚款   情况.................................................这样做   任务................... 好的............... 是你好吗?“;

(可能约100字)

  

String string2 =“如何做................... 不知道   需要......... 应该做什么...................... 很好   我 ..........好吧..“;

(可能约100字)

  

String string3 =“some string ................”;

(可能约100字)

  

String string4 =“some string ................”;

(可能约100字)

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

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

所以,现在string1的百分比值为100%.. 对于string2,百分比值是,57.xx%..等等..

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

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

queryBuilder

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

2 个答案:

答案 0 :(得分:1)

以下是如何做到的:

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

答案 1 :(得分:0)

试试这个

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


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

    int count = 0;
    String[] array = string1.split(" ");
    ArrayList<String> processedWords = new ArrayList<>();
    for(String str : array){

        if (string2.contains(str) && !processedWords.contains(str) && str.length() > 0){
                System.out.println(str);

            processedWords.add(str);
            count++;
        }

    }
    System.out.println("Total words: " +array.length);
    System.out.println("Count: " +count);

    System.out.println("Percent value: " +((float)count/array.length)*100);