【问题标题】:Compare string characters index by index and return unmatched characters with index逐个索引比较字符串字符并返回带有索引的不匹配字符
【发布时间】:2020-07-11 20:22:43
【问题描述】:
const s1 = 'testuser1122@abc.com';
const s2 = 'testuser112@abc.com';

// some function
someFunction(s1, s2); // this should return 2->12 (character->position)

我需要从第二个字符串中找到缺失的字符。

代码应该在 ES6 中

【问题讨论】:

  • 我喜欢@random 的回答,这对于我分享的代码来说已经足够了,但是考虑下面的用例, 有一个输入文本字段,其中用户输入 aaaa 如果用户尝试删除第一个a 那么我不应该将索引返回为3,但它应该是第一个索引,同样。
  • 确保您的答案也适用于类似的输入,` const s1 = 'test1122@abc.com'; const s2 = 'test5678@abc.com';`

标签: javascript string ecmascript-6 string-matching


【解决方案1】:

使用split 创建string 1 的数组。遍历它并根据string 2 中的相同索引检查字符,如果它们不同,则推入数组temp 数组并从string 1 数组中删除该字符。

const s1 = 'testuser1122@abc.com';
const s2 = 'testuser112@abc.com';

let arr = s1.split('');

const missingChars = [];

for(let i = 0; i < arr.length; i++) {
  if(arr[i] !== s2[i]) {
    missingChars.push(Object.assign({}, {"char": arr[i]}));
    arr.splice(i, 1);
    i = i-1;
  }
}

console.log(missingChars);

const s1 = 'testuser11223@1abc.com';
const s2 = 'testuser112@abc.com';

let arr = s1.split('');

const missingChars = [];

for(let i = 0; i < arr.length; i++) {
  if(arr[i] !== s2[i]) {
    missingChars.push(Object.assign({}, {"char": arr[i]}));
    arr.splice(i, 1);
    i = i-1;
  }
}

console.log(missingChars);

【讨论】:

  • 我尝试了第二个答案,但它也没有满足我在问题本身中添加的评论。
  • 顺便说一句,您的答案不适用于` const s1 = 'test1122@abc.com'; const s2 = 'test5678@abc.com';`
【解决方案2】:

const s1 = 'testuser1122@abc.com';
const s2 = 'testuser112@abc.com';

const s3 = 'testuser1122748@abcfg.com';
const s4 = 'testuser112@abc.com';

function diff(a, b){
let differences = [];
a.split("").map((c, i) => {
  if(b.split("")[i - differences.length] != c){
    differences.push({[c]: i});
  }
});
return differences;
}

console.log(diff(s1, s2));
console.log(diff(s3, s4));

【讨论】:

  • 我喜欢这个答案,但它不符合我在问题本身中添加的评论。
  • 您的答案不适用于值const s1 = 'test1122@abc.com'; const s2 = 'test5678@abc.com';
猜你喜欢
  • 2012-01-20
  • 2015-03-18
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多