Modo entrevista. Temporizador de 15 min, sin pistas y sin autocompletado
Reverse the word order, keep the spaces
DifícilStrings15 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.
Ejemplos
reverseWordOrder('This is sample text')Devuelve 'text sample is This'
reverseWordOrder(' Hello world ')Devuelve ' world Hello '
reverseWordOrder('a b c')Devuelve 'c b a'
Preguntada en Amazon · Fuente
Cargando el editor…
- Entrada
reverseWordOrder('This is sample text')Esperado'text sample is This' - Entrada
reverseWordOrder(' Hello world ')Esperado' world Hello ' - Entrada
reverseWordOrder('Hello')Esperado'Hello'
Las pruebas ocultas se ejecutan al enviar