簡體   English   中英

使用此代碼在 JS 中查找字符串中最長的單詞?

[英]Find the longest word in a string in JS using this code?

請讓我知道這段代碼有什么問題:

我知道有更簡單的方法可以達到預期的結果,但是我想了解如何使這個特定的代碼運行,以及我的錯誤是什么。 嘗試盡可能少地改變它,否則讓我知道為什么這不起作用。 另請注意,我正在嘗試console.log 3 個值,而不僅僅是一個。 謝謝你。

編輯:這是我實際測試代碼是否有效的freeCodeCamp練習: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-字符串中最長的單詞出於某種原因,大多數答案都在此處的代碼段中起作用,但在 freeCodeCamp 練習控制台中卻不起作用?

 function findLongestWordLength(str) { let arr = []; let longestWord = ""; let longestNum = 0; /*If there is a character at str[i] add it to the arr, else if there is whitespace don't add it to the arr. Instead, find the arr.length, if is greater than the previous overwrite longestNum, longestWord and empty the arr, if not just empty the arr and keep going*/ for (let i = 0; i <= str.length - 1; i++) { if (/./i.test(str[i])) { arr.push(str[i]); } else if (/\s/.test(str[i])) { if (arr.length - 1 >= longestNum) { longestNum = arr.length - 1; longestWord = arr.join(""); arr = []; } else { longestNum = longestNum; longestWord = longestWord; arr = []; } } } console.log(arr); console.log(longestWord); console.log(longestNum); return longestNum; } findLongestWordLength("The quick brown fox jumped over the lazy dog");

我假設使用/./i.test(str[i])您正在嘗試匹配除空格之外的所有內容。 . 匹配除換行符之外的所有內容,因此我將其切換為[^\s] ,它實際上匹配除空格之外的所有內容。 我還將控制台日志置於循環之外,因此 output 有點可讀。

function findLongestWordLength(str) {

  let arr = [];
  let longestWord = "";
  let longestNum = 0;

  for (let i = 0; i <= str.length - 1; i++) {
    if (/[^\s]/i.test(str[i])) {
      arr.push(str[i]);
    } else if (/[\s]/i.test(str[i])) {
      if (arr.length > longestNum) {
        longestNum = arr.length;
        longestWord = arr.join("");
        arr = [];
      } else {
        longestNum = longestNum;
        longestWord = longestWord;
        arr = [];
      }
    }

  }
  console.log(arr); // last word since you reset arr every step
  console.log(longestWord);
  console.log(longestNum);
  return longestNum;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

更好的方法是:

function findLongestWordLength(sentence) {
  const words = sentence.split(' ');
  return words.reduce((max, currentWord) => max > currentWord.length ? max : currentWord.length, 0);
}

只需進行最少的修改,您就需要進行以下更改:

  • 確保最后一個單詞的長度也得到驗證。 目前不是。 為此,您可以在執行循環之前向輸入字符串添加一個空格。
  • 更改測試/./i ,因為它將匹配除換行符之外的任何內容 你會想要檢查字母,可能還有數字,也許還有下划線,但不是標點符號。 所以/\w/將是一個改進。 你可以想出更好的正則表達式。 瀏覽器正在慢慢獲得對/\p{L}/u的支持,它可以匹配任何字母表中的字母。
  • 應該刪除else中的測試,因為您只想無條件地處理這里的任何其他情況 例如,逗號也將分隔單詞,並且在下一個單詞開始之前可能沒有空格。
  • 不要從數組長度中減去 1:它確實具有單詞的字符(僅),因此您需要完整長度。

這些是使其正確的最小更改:

 function findLongestWordLength(str) { let arr = []; let longestWord = ""; let longestNum = 0; str += " "; // trick to ensure that the last word is also inspected for (let i = 0; i <= str.length - 1; i++) { if (/\w/i.test(str[i])) { // match alphanumerical character, not anything. // The `i` suffix doesn't harm, but is useless here arr.push(str[i]); } else { // Remove any condition here. if (arr.length >= longestNum) { // you need the full length, not minus 1 longestNum = arr.length; // (idem) longestWord = arr.join(""); arr = []; } else { longestNum = longestNum; // not needed longestWord = longestWord; // not needed arr = []; } } //console.log(arr); //console.log(longestWord); //console.log(longestNum); } return longestNum; } console.log( findLongestWordLength("The quick brown fox jumped over the lazy dog") )

如您所知,有更短的方法可以做到這一點,例如使用這個函數式編程解決方案:

 function findLongestWordLength(str) { return Math.max(...str.match(/\w+|$/g).map(s => s.length)); } console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

只要字符不是空格( /\S/ - 大寫 S),您就需要添加項目。 如果是空格,則需要將長度與之前的longestWord.length進行比較,並將單詞賦值給longestWord 在空間的情況下,您初始化arr

注意:作業longestNum = longestNum; longestWord = longestWord; longestNum = longestNum; longestWord = longestWord; 是多余的,它們已經與它們自己相等。 此外, longestNum也是多余的,因為它是從longestWord ( longestWord.length ) 派生的。

 function findLongestWordLength(str) { let arr = []; let longestWord = ""; for (let i = 0; i < str.length; i++) { if (/\S/.test(str[i])) { // as long as it's not a space arr.push(str[i]); } else { if (arr.length > longestWord.length) { longestWord = arr.join(""); } arr = []; } } return longestWord.length; } var result = findLongestWordLength("The quick brown fox jumped over the lazy dog"); console.log(result);

如果您在第一個測試中使用稍微不同的正則表達式,則可以省略else if(..)條件: /\w/ ,尋找單詞中可能出現的任何字符。

 function findLongestWordLength(str) { let arr = [], longestWord = "", longestNum = 0; for (let i = 0; i <= str.length - 1; i++) { if (/\w/.test(str[i])) { arr.push(str[i]); } else { if (arr.length - 1 >= longestNum) { longestNum = arr.length - 1; longestWord = arr.join(""); arr = []; } else { longestNum = longestNum; longestWord = longestWord; arr = []; } } } console.log(arr); console.log(longestWord); console.log(longestNum); return longestNum; } var str="The quick brown fox jumped over the lazy dog"; findLongestWordLength(str); // alternatively you could simply do: console.log(str.split(/\s/).sort((a,b)=>b.length-a.length)[0])

arr的內容當然是最后測試的單詞,在本例中是“dog”。 有兩個長度為 5 的字符串,只找到第一個。

正如您在我的片段中看到的那樣,一種更短的方法是:

var longestWord=str.split(/\s/).sort((a,b)=>b.length-a.length)[0]

我會參考上述關於重組和冗余的優秀答案,但也會補充(因為 OP 需要解釋)這里使用的大多數(如果不是全部)正則表達式/拆分方法將推送單詞並包括前導/尾隨標點符號,或拆分單詞錯誤地。

使用\w通過連字符和單引號進行拆分,這可能會產生誤導性結果,具體取決於您的需要。

例如“你好……?” 長度比“longest”長,計算所有標點符號。 “你是”也是一個詞,而不是兩個詞,因此用空格分隔或僅依賴\w是有問題的。

將文本內容拆分為單詞時(如果是文字處理,我想這是一個家庭作業問題)不僅要依賴空格。 我在當前尚未發布的項目中使用此正則表達式: /[\s.,:;??_<>{}()[\]"`´^$°§½¼³%&¬+=*~#|/\\]/

上面的正則表達式允許連字符的單詞,雖然從技術上講,多個單詞連接在一起,但通常被閱讀/視為一個單詞,即在創建一個 janky-type-comund-noun 時,就像我剛才所做的那樣。

最后,語言很重要。 使用上面的正則表達式分割文本內容對英語來說效果很好,並且不會用單引號字符分割單詞,因為那樣我們會分割“你是個騙子!” ["you", "re", "a", "liar"]中,所以你仍然需要清理周圍單引號的結果數組(同樣,可能是多個,也許用戶寫了 "'Good晚上。'''"錯誤)。

總結:做 NLP (自然語言處理)的一個基本部分應該幾乎總是涉及“文本清理”步驟並依賴空格或內置\w特殊字符,即使只是在處理英文文本時,也不會削減它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM