【问题标题】:compare 2 strings and return the number of letters that aren't equal比较 2 个字符串并返回不相等的字母数
【发布时间】:2013-09-04 02:30:19
【问题描述】:

我正在尝试比较 2 个字符串是否相等,并返回不同位置的任何不同字母的数量(如果有),例如bob 和 buy 将返回 2。

我在其他地方没有找到任何其他示例,因此我尝试自己编写代码。我下面的代码没有返回任何东西,不确定它有什么问题?任何想法表示赞赏。

谢谢

    function equal(str1, str2) {

    /*If the lengths are not equal, there is no point comparing each character.*/
    if (str1.length != str2.length) {
        return false;
    }

    /*loop here to go through each position and check if both strings are equal.*/

    var numDiffChar = 0;
    var index = 0;
    while (index < str1.length) {
        if (str1.charAt(index) !== str2.charAt(index)) {
            numDiffChar += index;
            index++;
        } else {

            index++;
        }
    }

 };

 equal("javascript", "JavaScript");

【问题讨论】:

  • 如果你对类型强制没问题,你可以将完整的循环体缩短为numDiffChar += str1.charAt(index) !== str2.charAt(index); index ++;。
  • 太好了!感谢所有有用的答案。

标签: javascript string if-statement while-loop return


【解决方案1】:
numDiffChar += index;

numDiffChar 不会每次都增加 1,而是增加 index 的值。我猜你想这样做

numDiffChar++;

【讨论】:

    【解决方案2】:

    除了 Simon 的回答之外,您没有返回 numDiffChar 的值。此外,无论如何,您总是希望增加 index,所以我会将其放在 if 语句之外。如果字符串相等,您可以提前保释。建议:

    function equal(str1, str2) {
    
        /* If the strings are equal, bail */
        if (str1 === str2) {
            return 0;
        }
    
        /*If the lengths are not equal, there is no point comparing each character.*/
        if (str1.length != str2.length) {
            return false;
        }
    
        /*loop here to go through each position and check if both strings are equal.*/
        var numDiffChar = 0;
        var index = 0;
        while (index < str1.length) {
            if (str1.charAt(index) !== str2.charAt(index)) {
                numDiffChar++;
            }
            index++;
        }
        return numDiffChar;
    };
    

    【讨论】:

      【解决方案3】:

      函数相等(str1,str2){

      /*If the lengths are not equal, there is no point comparing each character.*/
      if (str1.length != str2.length) {
          return false;
      }
      
      /*loop here to go through each position and check if both strings are equal.*/
      else
      {
      var numDiffChar = 0;
      var index = 0;
      while (index < str1.length) {
          if (str1.charAt(index) !== str2.charAt(index)) {
              numDiffChar += index;
              index++;
          } else {
      
              index++;
          }
      }
      }
      

      };

      等于("javascript", "JavaScript");

      【讨论】:

      • 或者把ELSE放在"var numDiffChar=0"之前
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多