DEV Community

Abhinay Donadula
Abhinay Donadula

Posted on

Find longest word in a given string

Photo by Magdalena Kula Manchee on Unsplash

Rules

  1. Create a function that takes a parameter and returns longest word in that parameter
  2. Let's assume that this function will always get's a string as it's parameter

My Solution

code snippet

Top comments (14)

Collapse
 
dionakra profile image
David de los Santos Boix • Edited

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

Collapse
 
nektro profile image
Meghan (she/her)

This is what I thought to do as well 😄

Collapse
 
abhidon profile image
Abhinay Donadula

Good one, didn't think of reduce 👏

Collapse
 
dmfay profile image
Dian Fay
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');
Collapse
 
abhidon profile image
Abhinay Donadula

Awesome💖

Collapse
 
dannyaziz97 profile image
Danny Aziz • Edited

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

Collapse
 
jjtowle profile image
Jason Towle • Edited

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 :)

Collapse
 
veevidify profile image
V • Edited

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")
Collapse
 
vorsprung profile image
vorsprung • Edited

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)

}

Collapse
 
avalander profile image
Avalander • Edited

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.

Collapse
 
fabiengreard profile image
Fabien Gréard

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...

Collapse
 
abhidon profile image
Abhinay Donadula

Learned something new regarding jsperf, thank you. 🙏

Collapse
 
phallstrom profile image
Philip Hallstrom

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

def longest_word(str)
  str.split(/\s+/).max_by(&:length)
end
Collapse
 
nezlobnaya profile image
Vlad Burlutskiy • Edited

Bro, but what if it's the following sentence:
"I am a 'very('!) long(?) 'sentence'...!!!!""