Good morning, everyone.
Let's warm up for the start of the week by playing with strings.
s'yadoT egnellahc semoc from user xDranik on sraWedoC!
Write a function that takes in a string of one or more words and returns the same string, but with all words with five letters or more reversed. Strings passed in will consist of only letters and spaces.
Be sure to keep the order of the words the same and only reverse the letters.
Good luck, yppaH gniedoc!
Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (23)
JS quickie
Perl one-liner:
A bit more cleaned up, taking user input:
See runnable demo on PerlBanjo
Note that
($_)
is not needed forlength
andreverse
.Yeah, true, that's just my personal preference 🙂
And one that modifies a string inplace using C
JavaScript
Using reduce to generate a string from the array, but then I have to use trim as I end up with a space at either end :-/
Live demo on CodePen.
Nice one!
If you replace the
trim()
with asubstring(1)
then it'll work with strings that have spaces in front and behind since you're reliably adding a single space to the front, none to the back.See the warning here re the
split('')
call. Seems the recommended way now is [...string].This one was fun! I decided to approach it from a slightly different angle by building a general-purpose
when
function that could be used to decide when to map to a value (vs return the original value) based on a condition... just for kicks :-)Here's my go:
Gist (w/ some tests): gist.github.com/kerrishotts/ac0f30...
Haskell, with user input
Python one-liner:
for x in input().split(): print(x[::1]*(len(x)<5) or x[::-1], end=' ')
65 chars at most :)
Or,
print(*map(lambda x: x[::1]*(len(x)<5)or x[::-1], input().split()))
Also 65 at most :)
Here is my Rust solution and test cases!
The Rust std lib made this one pretty simple!
Elixir:
A quick one in C#