Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples...
For further actions, you may consider blocking this person and/or reporting abuse
Haskell
Without libraries:
reverseWords = unwords . map reverse . words
This looks very clean, well done. I think I would have gone for that one if keeping spaces wasn't an issue, but it is in this challenge.
The second code example from this post is wrong in the sense that spaces must be kept, and only a few provided solutions here are working because the example was not clear enough on what was expected.
I always lookup for the original challenge in Codewars to get a better specification to what I'm supposed to provide as a valid solution.
Original challenge specification.
Very elegant.
For Python, one line
Well done! It could also be
I think this would fail with doubles spaces in a sentence...
That's true :( looks like the right implementation is
you don't need to use
(' ')
to split by spaces :)That's what happens when you write too much js code 😅 edited thanks!
Looks great :)
Javascript
I avoided split("") as it breaks with non BMP characters. The spread operator works just as well for splitting strings into individual characters and won't break astral characters.
Notice how if I use split the output is messed up on my last test case.
For php
JavaScript (ES6) (golf)
Here are the PHP codes about using
foreach
andfor
loops to complete:More python:
Befunge-93
This version current works if the end of input pushes -1 on the stack (due to the interpreter I used), change 3 characters and it works for a carriage return
Or more simply:
JavaScript (imperative & linear):
ES6:
For Elixir
Another Python:
Try it online!
Perl:
Try it online!
For Java
Java Script
JavaScript :
Python one-liner:
Simple python example:
// JavaScript
const reverseWord = word => word.split("").reverse().join('');
// JavaScript
function reverseWord(word){
return word.split("").reverse().join('');
}
JS:
str.split(" ").map(w => w.split("").reverse().join("")).join(" ")