检测2个字符串中的第一个差异的位置 [英] Detect position of first difference in 2 strings

查看:33
本文介绍了检测2个字符串中的第一个差异的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中找到两个字符串中第一个差异的位置的最干净的方法是什么?

What is the cleanest way of finding the position of the first difference in any two strings in Javascript?

var a = 'in the';
var b = 'in he';
findFirstDiffPos(a, b); // 3

var c = 'in the beginning';
findFirstDiffPos(a, c); // 6 

推荐答案

您可以简单地遍历字符串并逐个字符地对其进行检查.

You can simply iterate through your strings and check it character-by-character.

document.body.innerHTML += findFirstDiffPos("in he", "in the") + "<br/>";
document.body.innerHTML += findFirstDiffPos("abcd", "abcde") + "<br/>";
document.body.innerHTML += findFirstDiffPos("zxc", "zxc");

function findFirstDiffPos(a, b)
{
   var shorterLength = Math.min(a.length, b.length);

   for (var i = 0; i < shorterLength; i++)
   {
       if (a[i] !== b[i]) return i;
   }

   if (a.length !== b.length) return shorterLength;

   return -1;
}

输出为 3 4 -1 :
3 :因为字符串在位置3处不同
4 :字符串 abcd abcde 的前缀,但是长度不同.字符串 abcd 中不存在第4个(从0开始)字符.您可以根据自己的要求更改此逻辑
-1 :字符串相等

The output is 3 4 -1:
3: because strings differ at position 3
4: string abcd is a prefix of abcde, but they are of different length. The 4-th (0-based) character does not exist in string abcd. You can change this logic in accordance with your requirements
-1: strings are equal

更新:正如@torazaburo在评论中提到的那样,代码甚至可以更容易-只需循环直到其长度的 Math.max()即可.之所以会成功,是因为 i> = s.length s [i] 将返回 undefined ,并且条件将导致 true .

Update: As @torazaburo mentioned in comments, the code can be even easier - just make a loop until the Math.max() of their length. It will work because s[i] for i >= s.length will return undefined and condition will result in true.

document.body.innerHTML += findFirstDiffPos("in he", "in the") + "<br/>";
document.body.innerHTML += findFirstDiffPos("abcd", "abcde") + "<br/>";
document.body.innerHTML += findFirstDiffPos("zxc", "zxc");

function findFirstDiffPos(a, b)
{
  var longerLength = Math.max(a.length, b.length);
  for (var i = 0; i < longerLength; i++)
  {
     if (a[i] !== b[i]) return i;
  }

  return -1;
}

这篇关于检测2个字符串中的第一个差异的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆