java中的PHP similar_text()[英] PHP similar_text() in java

问题描述

你知道 PHP similar_text Java 中的函数?

推荐答案

这与php源代码的string.c文件中的php_similar_str、php_similar_char、PHP_FUNCTION(similar_text)中的phpsimilar_text函数相同

private float similarText(String first, String second)   {
    first = first.toLowerCase();
    second = second.toLowerCase();
    return (float)(this.similar(first, second)*200)/(first.length()+second.length());
}

private int similar(String first, String second)  { 
    int p, q, l, sum;
    int pos1=0;
    int pos2=0;
    int max=0;
    char[] arr1 = first.toCharArray();
    char[] arr2 = second.toCharArray();
    int firstLength = arr1.length;
    int secondLength = arr2.length;

    for (p = 0; p < firstLength; p++) {
        for (q = 0; q < secondLength; q++) {
            for (l = 0; (p + l < firstLength) && (q + l < secondLength) && (arr1[p+l] == arr2[q+l]); l++);            
            if (l > max) {
                max = l;
                pos1 = p;
                pos2 = q;
            }

        }
    }
    sum = max;
    if (sum > 0) {
        if (pos1 > 0 && pos2 > 0) {
            sum += this.similar(first.substring(0, pos1>firstLength ? firstLength : pos1), second.substring(0, pos2>secondLength ? secondLength : pos2));
        }

        if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) {
            sum += this.similar(first.substring(pos1 + max, firstLength), second.substring(pos2 + max, secondLength));
        }
    }       
    return sum;
}

本文地址:https://www.itbaoku.cn/post/978381.html