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


Posted in Javascript onJanuary 18, 2021

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

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

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

算法挑战

  • 返回提供的句子中最长单词的长度。
  • 您的回复应该是一个数字。

提供的测试用例

  • findLongestWord(“The quick brown fox jumped over the lazy dog”)返回一个数字
  • findLongestWord(“The quick brown fox jumped over the lazy dog”)返回6
  • findLongestWord(“May the force be with you”)返回5
  • findLongestWord(“Google do a barrel roll”)返回6
  • findLongestWord(“What is the average airspeed velocity of an unladen swallow”)返回8
  • findLongestWord(“What if we try a super-long word such as otorhinolaryngology”)返回19
function findLongestWord(str) {
 return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

1.使用FOR循环查找最长的单词

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

  • split()的方法通过分离串分成子串分割字符串对象到字符串数组。

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

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

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

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

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

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");

没有注释:

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()方法找到最长的单词

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

  • sort()的方法进行排序的阵列的代替元素并返回数组。

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

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

我们将得到以下输出:

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

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

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

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

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

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");

没有注释:

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()方法找到最长的单词

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

  • reduce()的方法应用于对一个储液器的功能和所述阵列的每一值(从左到右),以将其降低到一个值。

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

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

[].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");

没有注释:

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");

到此这篇关于在JavaScript中查找字符串中最长单词的三种方法的文章就介绍到这了,更多相关js查找字符串最长单词内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Javascript 相关文章推荐
学习YUI.Ext 第二天
Mar 10 Javascript
获取当前网页document.url location.href区别总结
May 10 Javascript
浅谈关于JavaScript API设计的一些建议和准则
Jun 24 Javascript
js判断手机号运营商的方法
Oct 23 Javascript
jQuery+css3实现转动的正方形效果(附demo源码下载)
Jan 27 Javascript
Angular.js中用ng-repeat-start实现自定义显示
Oct 18 Javascript
使用gulp搭建本地服务器并实现模拟ajax
Apr 05 Javascript
bootstrap动态添加面包屑(breadcrumb)及其响应事件的方法
May 25 Javascript
使用JavaScript实现链表的数据结构的代码
Aug 02 Javascript
浅谈JS中的反柯里化( uncurrying)
Aug 17 Javascript
Vue CLI3中使用compass normalize的方法
May 30 Javascript
vue+vant实现商品列表批量倒计时功能
Jan 13 Javascript
vue-resource 拦截器interceptors使用详解
Jan 18 #Vue.js
js数组的基本使用总结
Jan 18 #Javascript
JavaScript/TypeScript 实现并发请求控制的示例代码
Jan 18 #Javascript
js加减乘除精确运算方法实例代码
Jan 17 #Javascript
Angular处理未可知异常错误的方法详解
Jan 17 #Javascript
react-native 实现购物车滑动删除效果的示例代码
Jan 15 #Javascript
vue element el-transfer增加拖拽功能
Jan 15 #Vue.js
You might like
PHP 上传文件的方法(类)
2009/07/30 PHP
vs中通过剪切板循环来循环粘贴不同内容
2011/04/30 PHP
php获取用户浏览器版本的方法
2015/01/03 PHP
ThinkPHP3.2.3实现分页的方法详解
2016/06/03 PHP
PHP版单点登陆实现方案的实例
2016/11/17 PHP
PHP封装cURL工具类与应用示例
2019/07/01 PHP
JavaScript 计算当天是本年本月的第几周
2009/03/22 Javascript
百度 popup.js 完美修正版非常的不错 脚本之家推荐
2009/04/17 Javascript
js 获取浏览器高度和宽度值(多浏览器)
2009/09/02 Javascript
添加JavaScript重载函数的辅助方法2
2010/07/04 Javascript
基于jquery循环map功能的代码
2011/02/26 Javascript
javascript开发技术大全 第4章 直接量与字符集
2011/07/03 Javascript
js类型转换与引用类型详解(Boolean_Number_String)
2014/03/07 Javascript
node.js中的console.error方法使用说明
2014/12/10 Javascript
基于jQuery实现的美观星级评论打分组件代码
2015/10/30 Javascript
原生js编写autoComplete插件
2016/04/13 Javascript
JavaScript必知必会(五) eval 的使用
2016/06/08 Javascript
jQuery设置和获取select、checkbox、radio的选中值方法
2017/01/01 Javascript
vue.js整合vux中的上拉加载下拉刷新实例教程
2018/01/09 Javascript
vue中slot(插槽)的介绍与使用
2018/11/12 Javascript
JavaScript实现的级联算法示例【省市二级联动功能】
2018/12/25 Javascript
微信小程序API—获取定位的详解
2019/04/30 Javascript
vue实现百度搜索功能
2020/12/28 Javascript
微信小程序实现发微博功能的示例代码
2020/06/24 Javascript
Vue中使用Echarts仪表盘展示实时数据的实现
2020/11/01 Javascript
Python实现的多进程和多线程功能示例
2018/05/29 Python
Python3.5面向对象程序设计之类的继承和多态详解
2019/04/24 Python
python itsdangerous模块的具体使用方法
2020/02/17 Python
Python变量及数据类型用法原理汇总
2020/08/06 Python
css3实现画半圆弧线的示例代码
2017/11/06 HTML / CSS
基于html5 canvas做批改作业的小插件
2020/05/20 HTML / CSS
SportsDirect.com马来西亚:英国第一体育零售商
2018/11/21 全球购物
检查机关领导群众路线教育实践活动个人整改措施
2014/10/28 职场文书
股份转让协议书范本
2015/01/27 职场文书
2015年青年志愿者协会工作总结
2015/04/27 职场文书
mysql性能优化以及配置连接参数设置
2022/05/06 MySQL