简体   繁体   English

比较两个字符串并计算相似字符的数量

[英]compare two strings and count number of similar characters

I am trying to write a js function which compares two strings and return the number of similar occurrences.我正在尝试编写一个 js function 来比较两个字符串并返回相似出现的次数。 But my function is considering duplicates as well.但我的 function 也在考虑重复。 For example, two words 'state' and 'tall'.例如,两个词“州”和“高”。 Ideally it should return a count of two but it is returning three considering two duplicate t's in 'state'.理想情况下,它应该返回两个计数,但考虑到两个重复的 t 在“状态”中,它返回三个。 Can anyone help me out with this谁能帮我解决这个问题

Here is ES5 solution:这是 ES5 解决方案:

 function solution(str1, str2) { var count = 0; var find = -1; for (var i = 0; i < str1.length; i++) { find = str2.indexOf(str1.charAt(i)); if (find > -1) { count++; str2 = str2.substr(0, find) + str2.substr(find + 1); } } return count; }; console.log(solution('state', 'tall'));

Next time you have to post your code first but here is something that should work for you:下次你必须先发布你的代码,但这里有一些对你有用的东西:

const countSimilarities = (s1, s2) =>
  s1
    .split("")
    .map((char1) => s2.split("").find((char2) => char1 === char2))
    .reduce((acc, c) => (c ? acc + 1 : acc), 0);

Could probably be optimized a bit beyond this, but this is a fairly simple version of a function to make this check.可能会在此之外进行一些优化,但这是一个相当简单的 function 版本来进行此检查。

 function matchingLettersCount(s1, s2) { const letters1 = [...new Set(s1.split(''))]; const letters2 = [...new Set(s2.split(''))]; return letters1.filter(x => letters2.includes(x)).length; } console.log(matchingLettersCount('state', 'tall'));

Can this help?这有帮助吗? I hope: Replace "gi" with "g" if you want it to be case sensitive.我希望:如果您希望它区分大小写,请将“gi”替换为“g”。

 function stringsCompare ( string, subString ) { let count = 0; string.replace(new RegExp(subString, "gi"), () => count++ ) return count; } //=========== test examples ================= console.log(stringsCompare("this is a string abc", "a")); // 2 occurances console.log(stringsCompare("foofoofoo", "foo")); // 3 occurances console.log(stringsCompare("aaaaaaaaa", "aa")); // 4 occurrences mmmm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM