简体   繁体   English

找出字符串中最长的单词

[英]find longest word in a string

Currently trying to figure out how to find the longest word in as string and my research has gotten me somewhere.目前正试图弄清楚如何在字符串中找到最长的单词,我的研究让我找到了某个地方。 I found a code on SO that shows the amount of alphabets in the longest word我在 SO 上找到了一个代码,它显示了最长单词中的字母数量

Example示例

function longest(str) {
  var words = str.split(' ');
  var longest = 0;

  for (var i=0;i<words.length;i++) {
    if (words[i].length > longest) {
      longest = words[i].length;
    }
  }
  return longest;
}
longest("This is Andela");

//This returns 6

How do i edit this code such that it returns the word instead of the amount of alphabets.That is我如何编辑此代码,使其返回单词而不是字母数量。那是

//Returns Andela instead of 6

Considering i am also new to javascript考虑到我也是 javascript 新手

There you go:你去吧:

 function longest(str) { var words = str.split(' '); var longest = ''; // changed for (var i = 0; i < words.length; i++) { if (words[i].length > longest.length) { // changed longest = words[i]; // changed } } return longest; } console.log(longest("This is Andela"));

I think the easiest solution is to split, sort the array by length and then pick the first element of the array.我认为最简单的解决方案是拆分,按长度对数组进行排序,然后选择数组的第一个元素。

function longest(str) { 

 var arr = str.split(" ");

 var sorted = arr.sort(function (a,b) {return b.length > a.length;});

return sorted[0];

}

If you want the length, just add .length to return sorted[0].如果您想要长度,只需添加 .length 即可返回 sorted[0]。

I recommend this approach:我推荐这种方法:

function LongestWord(text) {
    return text
      .split(/\s+/g)
      .reduce(function (record, word) {
        if (word.length > record.length) {                  
          record = word;
        }
        return record;
      }, '');
}
console.log(LongestWord('In this sentence it is not obvious which is the longest word.'));

If you want to return the length of the longest word, just add .length to the end of the return.如果要返回最长单词的长度,只需在返回的末尾添加 .length 即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM