查找字符串中最长的单词 [英] find longest word in a string

查看:58
本文介绍了查找字符串中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前试图弄清楚如何在字符串中找到最长的单词,而我的研究使我进入了某个地方.我在SO上找到了一个代码,可以显示最长单词中的字母数量

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

示例

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

考虑到我也是javascript新手

Considering i am also new to javascript

推荐答案

去那里:

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

这篇关于查找字符串中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆