简体   繁体   English

查找字符串中最长的单词 - JavaScript

[英]Find longest word in string - JavaScript

I am currently on a task in python and i need help with this and i am to 我目前正在使用python进行任务,我需要帮助,而且我需要帮助

Write a function called longest which will take a string of space separated words and will return the longest one. 编写一个名为longest的函数,它将采用一串空格分隔的单词并返回最长的单词。

For example: 例如:

longest("This is Andela") => "Andela"
longest("A") => "A"

This is the sample test 这是样本测试

const assert = require("chai").assert;

describe("Module 10 - Algorithyms", () => {
describe("longest('This Is Andela')", () => {
    let result = longest("This Is Andela");
    it("Should return 'Andela'", () => {
        assert.equal(result, 'Andela');
    });
});

describe("longest('This')", () => {
    let result = longest("This");
    it("Should return 'This'", () => {
        assert.equal(result, 'This');
    });
});

describe("longest(23)", () => {
    let result = longest(23);
    it("Should return ''", () => {
        assert.equal(result, '');
    });
});
});

This is what i have tried 这就是我尝试过的

function longest(str) {
str = "This is Andela";
var words = str.split(' ');
var longest = '';

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

But my code seem to only pass the first test case.Please what do i need to change to pass the other two first case considering i am new to javascript 但我的代码似乎只传递了第一个测试用例。请考虑我是javascript的新手,我需要更改以传递其他两个第一个案例

You need to remove this line in your function: 您需要在函数中删除此行:

str = "This is Andela";

You function should be (added check if str is string): 你的函数应该是(添加检查str是否是字符串):

function longest(str) {
    if(typeof str !== 'string') return '';
    var words = str.split(' ');
    var longest = '';

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

Simplified code with no arrays and no each statements. 没有数组且没有每个语句的简化代码。

 function longer(champ, contender) { return (contender.length > champ.length) ? contender: champ; } function longestWord(str) { var words = str.split(' '); return words.reduce(longer); } console.log(longestWord('This is longest')); console.log(longestWord('This is longest or may this is more longestest')); 

Check this one: 检查一下:

function longest(s){
    return typeof s != 'string' ? '' : s.split(' ').sort( (a,b) => b.length - a.length)[0]
}

The input is converted into string through concatenation with an empty string so that it works when a number is passed as well. 输入通过连接与空字符串转换为字符串,以便在传递数字时也能正常工作。

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

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