markdown guide
 

Same thing, but using a reducer instead of sorting.

const getLongestWordOf = (sentence = '') => {
  return sentence
    .split(' ')
    .reduce((longest, current) => {
      return current.length > longest.length ? current : longest;
    })

}

getLongestWordOf('I am just another solution to the same problem');

EDIT: This approach seems to be faster than the sorting one! jsperf.com/longestwordjs/1

 

This is what I thought to do as well πŸ˜„

 

Good one, didn't think of reduce πŸ‘

 
CREATE OR REPLACE FUNCTION get_longest_word (val TEXT) RETURNS TEXT AS $$
DECLARE longest_word TEXT;
BEGIN
  SELECT strs INTO longest_word
  FROM regexp_split_to_table(val, '\s+') AS strs
  ORDER BY char_length(strs) DESC
  LIMIT 1;

  RETURN longest_word;
END;
$$ LANGUAGE plpgsql;

SELECT get_longest_word('a bc def ghij klm no p');
 
 

I know one of the tags is 'Javascript' but here is how I would do it in Python:

def get_longest_word(sentence):
    return max(sentence.split(' '), key=lambda x: len(x))

get_longest_word('Iam a verrrrry loooongggg sentence')
# result: loooongggg

 

Can I chime in with a quick C# and LINQ one liner?

private Longest(string sentance) 
{
     return sentance.Split(' ').OrderByDescending(l => l.Length).FirstOrDefault();
}

Well, the return statement is a one liner :)

 

Recently started digging my way through GHC libraries

import Data.List

cmpLength :: String -> String -> Ordering
cmpLength l r = compare (length r) (length l)

findLongest :: String -> String
findLongest s = head . sortBy (cmpLength) . words $ s

main :: IO ()
main = do
  putStrLn (findLongest "Iam a verrrrry loooongggg sentence")
import Data.List

longerString :: String -> String -> String
longerString l r = if length l > length r then l else r

findLongest :: String -> String
findLongest s = foldr (\longest w -> longerString longest w) "" (words s)

main :: IO ()
main = do
  putStrLn (findLongest "Iam a verrrrry loooongggg sentence")
 

perl

$_=qq|Iam a verrrrryyy longggggggg sentence|;
print( (sort{length($b) <=> length($a)} split(qq|\s|))[0])

Go

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Iam a verrrrryyy longggggggg sentence"
    b := ""
    for _, w := range strings.Split(s, " ") {
        if len(w) > len(b) {
            b = w
        }
    }
    fmt.Println(b)

}

 

It may not be the most eye perfect code however the perf are close to the reducer solution jsperf.com/longestwordjs/11

carbon

I would still go to with the reducer solution, but sometimes doing 'old' things works very nice

I also try with for loop / for of, I expected it to be way more faster than everything else but it didn't.

from jsperf.com/foreach-vs-reduce-vs-fo...

 

Learned something new regarding jsperf, thank you. πŸ™

 

When used according to the specification, this function has O(1) complexity*.

/** @function getLongestWord
 * @param {String} s a string of words with the longest word in the first position.
 * @returns the longest word in a string, if it is the first word in the string, or a random word that occupies the first position in the string otherwise.
 */
const getLongestWord => (s = '') => s.split(' ')[0]

getLongestWord('loooongggg sentence very Iam') // 'loooongggg'

* It doesn't because split probably has complexity O(n) or something.

 

Ignoring punctuation and only considering spaces... ruby solution:

def longest_word(str)
  str.split(/\s+/).max_by(&:length)
end
Classic DEV Post from Sep 6 '18

7 Tips To Make You A Better Developer and Development Instructor

Abhinay Donadula profile image

Be an informed and productive developer.

Sign up (for free)