Mode entretien. Minuteur de 15 min, sans indices ni autocomplétion
Reverse the word order, keep the spaces
DifficileStrings15 min
Write a function reverseWordOrder(sentence) that returns a new string with the words in reverse order. The spaces between the words stay where they are: 'This is sample text' becomes 'text sample is This'.
- A word is a run of characters that are not spaces. Punctuation is part of the word.
- Words are separated only by spaces (no tabs, no line breaks). A gap can be one space or more.
- Every gap of whitespace keeps its length and its place, also at the start and at the end of the string. Only the words move:
' Hello world 'becomes' world Hello '. - The words themselves are not reversed.
- A string without words (empty or only spaces) is returned unchanged.
If you split on one space and join back with one space, the gaps move together with the words. A loop or a regular expression that finds the words and the gaps works better.
Exemples
reverseWordOrder('This is sample text')Renvoie 'text sample is This'
reverseWordOrder(' Hello world ')Renvoie ' world Hello '
reverseWordOrder('a b c')Renvoie 'c b a'
Posé chez Amazon · Source
Chargement de l'éditeur...
- Entrée
reverseWordOrder('This is sample text')Attendu'text sample is This' - Entrée
reverseWordOrder(' Hello world ')Attendu' world Hello ' - Entrée
reverseWordOrder('Hello')Attendu'Hello'
Les tests cachés se lancent à la soumission