在JavaScript中计算字符串距离/差异?

时间:2012-04-16 06:30:17

标签: jquery

我必须比较两个字符串,因为str1包含str2的百分比。

str1="Hello wolrd"
str2="hello"

表示distance(str1, str2)应该返回50%..就像那样。

2 个答案:

答案 0 :(得分:0)

我不是数学家,也不能向你展示这样的神奇公式,但是这个例子会让你开始递归 - 请仔细查看代码注释:

/* same_words array should hold the following:
   ["john", "bbc", "hot", "red,", "xyz,", "apples,", "and", "likes"]

   NOTES:
    - The more words you add, the less the percentage will be... that's how percent works.
    - milk and MILK are the same word, but:  MILK and MILK, aren't the same because of the comma (same goes for periods).
*/

var  jSmith =  'JOHN smith LIKES bananas, HOT chocolate, AND APPLES, nonsense, RED, 321, XYZ, BBC or npr',
jSmithArray =  jSmith.trim().toLowerCase().split(' '); //Makes an array of words for jSmith

var  jDoe =  'JOHN doe LIKES oranges, milk, AND APPLES, XYZ, 123, RED, green, HOT and... cnn sucks, BBC rocks',
jDoeArray =  jDoe.trim().toLowerCase().split(' '); //Makes an array of words for jDoe

var bothJohns = jSmithArray.concat(jDoeArray); //console.log(bothJohns);

var c = 0; //counter
var same_words = []; //collection container


//collects all the words that occur in both sentences
function collectSimilarWords(word) {
  same_words.push(word);
}


//The w parameter holds the word "john" for the 1st time.
//The fn parameter holds always the collectSimilarWords() function.
function recur(w, fn) {
  for (var p in jSmithArray) { //Every property of the jSmithArray Array holds a word string.
    if (w) {
       if (w == jSmithArray[p]) { //If the word we passed in as a parameter is the same word as one of the jSmithArray elements...
           fn( jSmithArray[p] ); //...then pass this word to the collectSimilarWords() function.
       }
       c += 1; //Increase c so we can move to...
       recur(jDoeArray[c], collectSimilarWords); //...the next word recursively.
    }
  }
}

//Call recur() and pass in the first word of the jDoeArray as the 1st param, and a function as the 2nd param.
recur(jDoeArray[c], collectSimilarWords);


function calcWhatever(samewords) { //Feel free to calculate however you want.
   var percent = ( (samewords.length * 100) / bothJohns.length ).toFixed(2);
   var msg = "Out of Smith\'s plus Doe's words (total: " + bothJohns.length + "), about " + percent + "% (or " + same_words.length + ") of them are found in both of their sentences!";
   return msg;
}

//Hopefuly setTimeout() will log the same_words array when the recursive function has finished.
window.setTimeout(function() {
    console.log(same_words);
    console.log(  calcWhatever(same_words)  );
}, 1000);

而不是for in循环,你可以像这样轻松地使用for循环:

for (var p = 0; p<jSmithArray.length; p++) { /* ... */ }

答案 1 :(得分:-1)

请尝试使用以下代码。

<script>
var str1 = 'helloworld';
var str2 = 'hello';
var percent = 0;
var newstr = str1.search(str2);
if(newstr != -1){

    percent = (str2.length * 100)/str1.length;
   alert(percent+'%');

}else{
  alert(percent+'%');
}

</script>

如果我理解你的问题,我相信这会对你有帮助。

感谢。