2016-05-19 20 views
0

我試圖在不將字符串轉換爲數組的情況下獲取常用單詞(來自兩個字符串)。下面的代碼是獲取並顯示常用詞,但問題是,此代碼不會刪除所有重複項,因爲它顯示所有常用詞而不刪除重複項。我嘗試搜索,但解決方案是使用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>

+5

如果有一個限制,這可能是有用的,以解釋爲什麼限制存在。 –

+0

* filter *是一個數組方法,那麼如何在不將字符串轉換爲數組或類似數組的對象的情況下使用它? – RobG

+0

字符串的執行時間將小於數組,因此我寧願使用字符串而不將其轉換爲數組。 – Johny

回答

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) { 
 
    \t stc+=str1[i++]; 
 
    } else { 
 
    \t lut[stc] = "unmatch"; 
 
    \t stc = ""; 
 
    \t ++i; 
 
    } 
 
} 
 

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

相關問題