Elixir-Find second letter of each word

Viewed 165

I need to write a function that accepts a string as a parameter and returns the second letter of each word.

ModuleName.function_name("Hello World! This is a test.")
# --> "eohse"

I tried it using Enum functions but it didn’t work out.

Can anyone find me a solution?

2 Answers

You can use binary pattern matching combined with a for comprehension and String.split/1:

for <<_::utf8, x::utf8, _::binary>> <- String.split("Please give me a job"),
    do: <<x::utf8>>,
    into: ""

Output:

"lieo"

Slightly less gnomically

String.split("Hello World! This is a test.") 
|> Enum.map( fn s-> String.at(s,1) end )    
|> Enum.join()

produces

"eohse"
Related