在JavaScript中查找字符串中最长单词的三种方法

This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.

本文基于Free Code Camp基本算法脚本“ 查找字符串中最长的单词 ”。

In this algorithm, we want to look at each individual word and count how many letters are in each. Then, compare the counts to determine which word has the most characters and return the length of the longest word.

在此算法中 ,我们要查看每个单词并计算每个单词中有多少个字母。 然后,比较计数以确定哪个单词的字符最多,并返回最长单词的长度。

In this article, I’m going to explain three approaches. First with a FOR loop, second using the sort() method, and third using the reduce() method.

在本文中,我将解释三种方法。 首先使用FOR循环,其次使用sort()方法,第三次使用reduce()方法。

算法挑战 (Algorithm Challenge)

Return the length of the longest word in the provided sentence.

返回提供的句子中最长单词的长度。

Return the length of the longest word in the provided sentence.

返回提供的句子中最长单词的长度。

提供的测试用例 (Provided test cases)
  • findLongestWord(“The quick brown fox jumped over the lazy dog”) should return a number

    findLongestWord(“敏捷的棕色狐狸跳过了懒狗”)应返回一个数字

  • findLongestWord(“The quick brown fox jumped over the lazy dog”) should return 6

    findLongestWord(“敏捷的棕色狐狸跳过了懒狗”)应返回6

  • findLongestWord(“May the force be with you”) should return 5

    findLongestWord(“愿力量与你同在”)应返回5

  • findLongestWord(“Google do a barrel roll”) should return 6

    findLongestWord(“ Google做桶装”)应该返回6

  • findLongestWord(“What is the average airspeed velocity of an unladen swallow”) should return 8

    findLongestWord(“空载吞咽的平均空速是多少”)应返回8

  • findLongestWord(“What if we try a super-long word such as otorhinolaryngology”) should return 19

    findLongestWord(“如果我们尝试超长单词如耳鼻喉科怎么办?”) 应该返回19

function findLongestWord(str) {
  return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

1.使用FOR循环查找最长的单词 (1. Find the Longest Word With a FOR Loop)

For this solution, we will use the String.prototype.split() method

对于此解决方案,我们将使用String.prototype.split()方法

  • The split() method splits a String object into an array of strings by separating the string into sub strings.

    split()方法通过将String对象拆分为子字符串,将String对象拆分为字符串数组。

We will need to add an empty space between the parenthesis of the split() method,

我们将需要在split()方法的括号之间添加一个空格,

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);

which will output an array of separated words:

它将输出一个由单词组成的数组:

var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

If you don’t add the space in the parenthesis, you will have this output:

如果不在括号中添加空格,则将显示以下输出:

var strSplit = 
[“T”, “h”, “e”, “ “, “q”, “u”, “i”, “c”, “k”, “ “, “b”, “r”, “o”, “w”, “n”, “ “, “f”, “o”, “x”, “ “, “j”, “u”, “m”, “p”, “e”, “d”, “ “, “o”, “v”, “e”, “r”, “ “, “t”, “h”, “e”, “ “, “l”, “a”, “z”, “y”, “ “, “d”, “o”, “g”];
function findLongestWord(str) {
  // Step 1. Split the string into an array of strings
  var strSplit = str.split(' ');
  // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
  // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
	
  // Step 2. Initiate a variable that will hold the length of the longest word
  var longestWord = 0;

  // Step 3. Create the FOR loop
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longestWord){ // If strSplit[i].length is greater than the word it is compared with...
	longestWord = strSplit[i].length; // ...then longestWord takes this new value
     }
  }
  /* Here strSplit.length = 9
     For each iteration: i = ?   i < strSplit.length?   i++  if(strSplit[i].length > longestWord)?   longestWord = strSplit[i].length
     1st iteration:        0             yes             1   if("The".length > 0)? => if(3 > 0)?     longestWord = 3
     2nd iteration:        1             yes             2   if("quick".length > 3)? => if(5 > 3)?   longestWord = 5   
     3rd iteration:        2             yes             3   if("brown".length > 5)? => if(5 > 5)?   longestWord = 5   
     4th iteration:        3             yes             4   if("fox".length > 5)? => if(3 > 5)?     longestWord = 5  
     5th iteration:        4             yes             5   if("jumped".length > 5)? => if(6 > 5)?  longestWord = 6 
     6th iteration:        5             yes             6   if("over".length > 6)? => if(4 > 6)?    longestWord = 6 
     7th iteration:        6             yes             7   if("the".length > 6)? => if(3 > 6)?     longestWord = 6
     8th iteration:        7             yes             8   if("lazy".length > 6)? => if(4 > 6)?    longestWord = 6 
     9th iteration:        8             yes             9   if("dog".length > 6)? => if(3 > 6)?     longestWord = 6 
     10th iteration:       9             no               
     End of the FOR Loop*/

  //Step 4. Return the longest word
  return longestWord; // 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");
没有评论: (Without comments:)
function findLongestWord(str) {
  var strSplit = str.split(' ');
  var longestWord = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longestWord){
	longestWord = strSplit[i].length;
     }
  }
  return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

2.使用sort()方法找到最长的单词 (2. Find the Longest Word With the sort() Method)

For this solution, we will use the Array.prototype.sort() method to sort the array by some ordering criterion and then return the length of the first element of this array.

对于此解决方案,我们将使用Array.prototype.sort()方法按照某种排序标准对数组进行排序,然后返回此数组的第一个元素的长度。

  • The sort() method sorts the elements of an array in place and returns the array.

    sort()方法对数组中的元素进行适当排序并返回该数组。

In our case, if we just sort the array

就我们而言,如果我们只是对数组排序

var sortArray = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”].sort();

we will have this output:

我们将得到以下输出:

var sortArray = [“The”, “brown”, “dog”, “fox”, “jumped”, “lazy”, “over”, “quick”, “the”];

In Unicode, numbers come before upper case letters, which come before lower case letters.

在Unicode中,数字在大写字母之前,而在小写字母之前。

We need to sort the elements by some ordering criterion,

我们需要按照某种排序标准对元素进行排序,

[].sort(function(firstElement, secondElement) {     return secondElement.length — firstElement.length; })

where the length of the second element is compared to the length of the first element in the array.

比较第二个元素的长度和数组中第一个元素的长度。

function findLongestWord(str) {
  // Step 1. Split the string into an array of strings
  var strSplit = str.split(' ');
  // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
  // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
  
  // Step 2. Sort the elements in the array
  var longestWord = strSplit.sort(function(a, b) { 
    return b.length - a.length;
  });
  /* Sorting process
    a           b            b.length     a.length     var longestWord
  "The"      "quick"            5            3         ["quick", "The"]
  "quick"    "brown"            5            5         ["quick", "brown", "The"]  
  "brown"    "fox"              3            5         ["quick", "brown", "The", "fox"]
  "fox"      "jumped"           6            3         ["jumped", quick", "brown", "The", "fox"]
  "jumped"   "over"             4            6         ["jumped", quick", "brown", "over", "The", "fox"]
  "over"     "the"              3            4         ["jumped", quick", "brown", "over", "The", "fox", "the"]
  "the"      "lazy"             4            3         ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"]
  "lazy"     "dog"              3            4         ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]
  */
  
  // Step 3. Return the length of the first element of the array
  return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy", "The", "fox", "the", "dog"];
                                // longestWord[0]="jumped" => jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");
没有评论: (Without comments:)
function findLongestWord(str) {
  var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
  return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

3.使用reduce()方法找到最长的单词 (3. Find the Longest Word With the reduce() Method)

For this solution, we will use the Array.prototype.reduce().

对于此解决方案,我们将使用Array.prototype.reduce()。

  • The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

    reduce()方法对一个累加器应用一个函数,该数组的每个值(从左到右)将其减小为单个值。

reduce() executes a callback function once for each element present in the array.

reduce()对数组中存在的每个元素执行一次回调函数。

You can provide an initial value as the second argument to reduce, here we will add an empty string “”.

您可以提供一个初始值作为减少的第二个参数,这里我们将添加一个空字符串“”。

[].reduce(function(previousValue, currentValue) {...}, “”);
function findLongestWord(str) {
  // Step 1. Split the string into an array of strings
  var strSplit = str.split(' ');
  // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
  // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

  // Step 2. Use the reduce method
  var longestWord = strSplit.reduce(function(longest, currentWord) {
    if(currentWord.length > longest.length)
       return currentWord;
    else
       return longest;
  }, "");
  
  /* Reduce process
  currentWord      longest       currentWord.length     longest.length    if(currentWord.length > longest.length)?   var longestWord
  "The"             ""                  3                     0                              yes                          "The"
  "quick"           "The"               5                     3                              yes                         "quick"
  "brown"           "quick"             5                     5                              no                          "quick"
  "fox"             "quick"             3                     5                              no                          "quick"
  "jumped"          "quick"             6                     5                              yes                         "jumped"
  "over"            "jumped"            4                     6                              no                          "jumped"
  "the"             "jumped"            3                     6                              no                          "jumped"
  "lazy"            "jumped"            4                     6                              no                          "jumped"
  "dog"             "jumped"            3                     6                              no                          "jumped"
  */
  
  // Step 3. Return the length of the longestWord
  return longestWord.length; // var longestWord = "jumped" 
                             // longestWord.length => "jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");
没有评论: (Without comments:)
function findLongestWord(str) {
  var longestWord = str.split(' ').reduce(function(longest, currentWord) {
    return currentWord.length > longest.length ? currentWord : longest;
  }, "");
  return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

希望对您有所帮助。 这是我的“如何解决FCC算法”系列文章的一部分,有关自由代码训练营算法挑战,我在其中提出了几种解决方案并逐步解释了幕后情况。

Three ways to repeat a string in JavaScriptIn this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…

在JavaScript中重复字符串的三种方法 在本文中,我将解释如何解决freeCodeCamp的“重复字符串重复字符串”挑战。 这涉及…

Two ways to confirm the ending of a String in JavaScriptIn this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.

在JavaScript中确认字符串结尾的两种方法 在本文中,我将解释如何解决freeCodeCamp的“确认结尾”挑战。

Three Ways to Reverse a String in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

在JavaScript中反转字符串的三种方法 本文基于Free Code Camp基本算法脚本“反转字符串”

Three Ways to Factorialize a Number in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”

在JavaScript中分解数字的三种方法 本文基于Free Code Camp基本算法脚本“简化数字”

Two Ways to Check for Palindromes in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

用JavaScript检查回文的两种方法 本文基于Free Code Camp基本算法脚本“检查回文”。

Three Ways to Title Case a Sentence in JavaScriptThis article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.

用JavaScript给句子加标题的三种方法 本文基于Free Code Camp基本算法脚本“标题加句子”。

Three ways you can find the largest number in an array using JavaScriptIn this article, I’m going to explain how to solve Free Code Camp’s “Return Largest Numbers in Arrays” challenge. This…

使用JavaScript 数组中找到最大数字的三种方法 在本文中,我将解释如何解决Free Code Camp的“在数组中返回最大数字”挑战。 这个…

If you have your own solution or any suggestions, share them below in the comments.

如果您有自己的解决方案或任何建议,请在下面的评论中分享。

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

或者,您也可以在单击下面的绿色心脏之后立即在Medium TwitterGithubLinkedIn上关注我;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

‪#StayCurious‬,‪#KeepOnHacking‬和‪#MakeItHappen‬!

翻译自: https://www.freecodecamp.org/news/three-ways-to-find-the-longest-word-in-a-string-in-javascript-a2fb04c9757c/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值