最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何获得两个字符串中相同字符的数量?

运维笔记admin13浏览0评论

如何获得两个字符串中相同字符的数量?

如何获得两个字符串中相同字符的数量?

我正在尝试创建一个函数来返回您提供的2个字符串中相同字符的数量。

  let [string1, string2] = target.split(",").map(p => p.trim());
  let [length, char1, char2] = "";
  let total = "0";
  if (!string1 || !string2) return this.errorReply(`Please provide two words or sentences separated by a comma.`);
  if (string1.length > string2.length) {
    length = string1.length;
  } else {
    length = string2.length;
  }
  let i;
  for (i = 0; i < length; i++) {
    char1 = string1.charAt(i);
    char2 = string2.charAt(i);
    if (char1 === char2) total++;
  }
  return this.sendReply(`|html|These two strings have <b>${total}</b> characters in common.`);

这是我到目前为止的内容,但这会检查第一个字符是否等于第一个字符,第二个字符是否等于第二个字符,依此类推。我需要它基本上取第一个字符串的第一个字符,并检查它是否与第二个字符串中的任何字符相同,并且一旦检查了所有的字符,便移至第一个字符串的第二个字符并重复。关于如何执行此操作有任何帮助吗?

回答如下:
let str1 = "ABCDEF";
let str2 = "CF XYZ KLMN";

let total = str1.split("").filter((char)=> str2.split("").indexOf(char) > -1 ).length;
发布评论

评论列表(0)

  1. 暂无评论