Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Get shortest/longest string in array

$
0
0

What is the best way to retrieve the shortest or longest string in an array? If there are multiple candidates having the same minimum/maximum length, it’s okay to return just the first one.

This can be solved with the snippet below. Is there a better way to do it, though? Thanks in advance.

arr = ["hello", "beautiful", "world", "!"]
minl, maxl = extrema(length, arr)

shortest = filter(x -> length(x) == minl, arr) |> first
longest = filter(x -> length(x) == maxl, arr) |> first

# or even...
shortest = arr[findfirst(x -> length(x) == minl, arr)]
longest = arr[findfirst(x -> length(x) == maxl, arr)]

16 posts - 9 participants

Read full topic


Viewing all articles
Browse latest Browse all 2795

Latest Images

Trending Articles



Latest Images