使用此代码在JS中找到字符串中最长的单词?

请让我知道此代码出了什么问题:

我知道有多种简单的方法可以达到期望的结果,但是我想了解如何使这个特定的代码运行,以及我的错误是什么。尝试对其进行尽可能少的更改,否则让我知道为什么这行不通。另请注意,我正在尝试console.log 3个值,而不仅仅是一个。谢谢。

编辑:这是我实际上要测试代码是否有效的freeCodeCamp练习:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string由于某些原因,大多数答案都在此处的代码段中起作用,但在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");

wuboshuai2008 回答:使用此代码在JS中找到字符串中最长的单词?

我假设使用/./i.test(str[i])来尝试匹配除空格以外的所有内容。 .匹配换行符以外的所有内容,因此我将其切换为[^\s],它实际上匹配了除空格以外的所有内容。我还将控制台日志移到了循环之外,因此输出有些可读。

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);
}
,

以最少的修改,您需要进行以下更改:

  • 确保还验证了 last 单词的长度。目前不是。为此,您只需在执行循环之前在输入字符串中添加一个空格即可。
  • 更改测试/./i,因为该测试将匹配除换行符外的所有内容。您需要检查字母和数字,也可以检查下划线,但不检查标点。因此/\w/将是一个改进。您可以想到更好的正则表达式。浏览器正在慢慢获得对/\p{L}/u的支持,该else与任何字母的字母匹配。
  • 应该删除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"));

您知道,执行此操作的方法比较短,例如,使用此功能编程解决方案:

SELECT User,Host FROM mysql.user;

,

只要字符不是空格(/\S/-大写S),就需要添加项目。如果是空格,则需要将长度与前一个longestWord.length进行比较,并将单词分配给longestWord。对于空格,请初始化arr

注意:分配longestNum = longestNum; longestWord = longestWord;是多余的,它们已经等于自己。另外,longestNum也是多余的,因为它是从longestWordlongestWord.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想要解释),此处使用的大多数regex / split方法(如果不是全部的话)都会推词并包括前导/后缀标点,或错误地拆分单词。

使用\w按连字符和单引号分隔,这可能会产生误导性的结果,具体取决于您的需求。

例如“你好...?”具有比“最长”更长的长度(计算所有标点符号)。另外,“ You're”是一个单词,而不是两个单词,因此,用空格分隔或仅依靠\w是有问题的。

将文本内容拆分为单词时,不仅应该依赖空格,而且还应该(如果是文字处理,我想这是一个家庭作业问题)。我在当前尚未发布的项目中使用此正则表达式:/[\s.,:;!?_<>{}()[\]"`´^$°§½¼³%&¬+=*~#|/\\]/

上面的正则表达式允许使用连字词,尽管从技术上讲多个词连在一起,但经常像单个词一样读/处理,即像我刚才那样创建一个简陋的类型名词时。

最后,语言很重要。使用上述正则表达式拆分文本内容在英语上效果很好,并且不会通过单引号字符拆分单词,因为那样的话,我们将拆分“您是骗子!”放入["you","re","a","liar"]中,因此您仍然需要清除结果周围的单引号引起的单词数组(同样可以是多个单词,也许用户错误地写了“'Good night!''””)。>

摘要:进行NLP(自然语言处理)的基本部分几乎应该始终涉及“文本清除”步骤,并依赖于空格或内置的\w特殊字符,即使是在处理英文文本时,不会削减。

本文链接:https://www.f2er.com/3128306.html

大家都在问