从字符串中删除重复的单词而不将其转换为数组

时间:2016-05-19 06:09:07

标签: javascript string

从下面的代码我试图得到常见的单词(从给出的两个字符串)而不将字符串转换为数组。下面的代码是获取并显示常用单词但问题是,此代码并未删除所有重复项,因为它显示所有常用单词而不删除重复项。我尝试搜索,但解决方案是使用split()和filter()。有没有其他方法可以删除重复项。

非常感谢。

function common() {
  var str1 = "is hello and he is the only hello is"
  var str2 = "is hello you and is and he and is the only";
  var min = 0;
  var max = 0;
  var count = 0;
  var count1 = 0;
  var count2 = 0;
  var out = '';
  var out2 = '';
  var out3 = '';
  var len1 = str1.length;
  var len2 = str2.length;
  var output = '';
  var temp = 0;
  var temp1 = 0;
  for (m = 0; m < str1.length; m++) {
    temp1 = 0;
    if (str1.charAt(m) == " " || m == str1.length - 1) {
      count1++;
      if (m == str1.length - 1) {
        out1 = str1.slice(temp, m + 1);
      } else {
        out1 = str1.slice(temp, m);
      }
      for (i = temp1; i < str2.length; i++) {
        if (str2.charAt(i) == " " || i == str2.length - 1) {
          if (i == str2.length - 1) {
            out2 = str2.slice(temp1, i + 1);
          } else {
            out2 = str2.slice(temp1, i);
          }
          temp1 = i + 1;
          if (out1 == out2) {
            if (out3.indexOf(out1) == -1) {
              out3 += out1 + ' ';
            } else if (out3.indexOf(out1) >= 0) {
              var r = out3.indexOf(out1);
              while (out3.charAt(r) != " ") {
                r++;
              }
              if (r != out1.length) {
                out3 += out1 + ' ';
              }
            }
          }
        }
      }
      temp = m + 1;
    }
  }
  console.log(out3);
  out = document.getElementById("tarea3");
  out.value = out3;
}
<textarea id="tarea"></textarea>
<textarea id="tarea2"></textarea>
<textarea id="tarea3"></textarea>
<button type="button" onclick="common()">Run</button>

1 个答案:

答案 0 :(得分:0)

没有阵列没有正则表达式你可以得到像这样的常用词。其余的由您处理。

var str1 = "is hello and he is the only hello is",
    str2 = "is hello you and is and he and is the only",
     lut = {},
     stc = "",
       i = 0;

while (i <= str1.length) {
  if (str1[i] !== " " && i < str1.length) {
  	stc+=str1[i++];
  }  else {
  	lut[stc] = "unmatch";
  	stc = "";
  	++i;
  }
}

  i = 0;
stc = "";
while (i <= str2.length) {
  if (str2[i] !== " " && i < str2.length) {
  	stc+=str2[i++];
  }  else {
  	lut[stc] = lut[stc] ? "common" : "unmatch";
  	stc = "";
  	++i;
  }
}
console.log(lut);