Code Lab

Mode entretien. Minuteur de 10 min, sans indices ni autocomplétion

Reverse each word and the whole string

MoyenStrings10 min

Write a function reverseBoth(sentence) that reverses a string in two ways and returns both results in an object { eachWord, whole }.

  • eachWord: the characters of every word are reversed, but the words stay in their order. 'Hello World' gives 'olleH dlroW'.
  • whole: the whole string reversed character by character. 'Hello World' gives 'dlroW olleH'.
  • Words are separated by spaces. A word is any group of characters between spaces, so punctuation is part of the word: 'Hi!' gives '!iH'.
  • In eachWord every space stays where it is: double spaces, spaces at the start and spaces at the end too. The input has only spaces as whitespace, no tabs or line breaks.
  • For the empty string both fields are ''.

You can split the string into words and join them back, but keep every space.

Exemples

reverseBoth('Hello World')

Renvoie { eachWord: 'olleH dlroW', whole: 'dlroW olleH' }

reverseBoth('Hi  Ann')

Renvoie { eachWord: 'iH nnA', whole: 'nnA iH' }

The double space stays in both results.

Posé chez JP Morgan · Source

Chargement de l'éditeur...
  1. EntréereverseBoth('Hello World')
    Attendu{ eachWord: 'olleH dlroW', whole: 'dlroW olleH' }
  2. EntréereverseBoth('I Love Java')
    Attendu{ eachWord: 'I evoL avaJ', whole: 'avaJ evoL I' }
  3. EntréereverseBoth('Selenium')
    Attendu{ eachWord: 'muineleS', whole: 'muineleS' }

Les tests cachés se lancent à la soumission