简体   繁体   中英

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. But my function is considering duplicates as well. 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'. Can anyone help me out with this

Here is ES5 solution:

 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 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.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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