当前位置:  开发笔记 > 编程语言 > 正文

有没有办法计算2个字符串之间的%匹配

如何解决《有没有办法计算2个字符串之间的%匹配》经验,为你挑选了1个好方法。

有没有办法计算2个字符串之间的%匹配?

我有一种情况,如果有85%,需要计算2个字符串之间的匹配

匹配然后我将结合2个表,我已经编写了组合2个表的代码

我的示例字符串是:

var str1 = 'i love javascript';
var str2 = 'i love javascripttt';

var matchPer = match(str1,str2); // result might be 80% , 85%, 90% ,95% etc

Ala Eddine J.. 9

像这样的东西?

var str1 = 'i love javascript';
var str2 = 'i love javascripttt';

function match(str1, str2){
    var tmpValue = 0;
    var minLength = str1.length;
	if(str1.length > str2.length){
		var minLength = str2.length;
	}	
    var maxLength = str1.length;
	if(str1.length < str2.length){
		var maxLength = str2.length;
	}
    for(var i = 0; i < minLength; i++) {
        if(str1[i] == str2[i]) {
            tmpValue++;
        }
    }
    var weight = tmpValue / maxLength;
    return (weight * 100) + "%";
}

var matchPer = match(str1,str2);
console.log(matchPer); //outputs: 89.47%
console.log( match("aaaaa", "aaaaa") ); //outputs: 100%
console.log( match("aaaaa", "aXaaa") ); //outputs: 80%
console.log( match("aaaaa", "aXXaa") ); //outputs: 60%
console.log( match("aaaaa", "aXXXa") ); //outputs: 40%
console.log( match("aaaaa", "aXXXX") ); //outputs: 20%



1> Ala Eddine J..:

像这样的东西?

var str1 = 'i love javascript';
var str2 = 'i love javascripttt';

function match(str1, str2){
    var tmpValue = 0;
    var minLength = str1.length;
	if(str1.length > str2.length){
		var minLength = str2.length;
	}	
    var maxLength = str1.length;
	if(str1.length < str2.length){
		var maxLength = str2.length;
	}
    for(var i = 0; i < minLength; i++) {
        if(str1[i] == str2[i]) {
            tmpValue++;
        }
    }
    var weight = tmpValue / maxLength;
    return (weight * 100) + "%";
}

var matchPer = match(str1,str2);
console.log(matchPer); //outputs: 89.47%
console.log( match("aaaaa", "aaaaa") ); //outputs: 100%
console.log( match("aaaaa", "aXaaa") ); //outputs: 80%
console.log( match("aaaaa", "aXXaa") ); //outputs: 60%
console.log( match("aaaaa", "aXXXa") ); //outputs: 40%
console.log( match("aaaaa", "aXXXX") ); //outputs: 20%
推荐阅读
ifx0448363
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有