Reverse word order in string

Reverse the entire string, then reverse the letters of each individual word.

After the first pass the string will be

s1 = "Z Y X si eman yM"

and after the second pass it will be

s1 = "Z Y X is name My"

11

reverse the string and then, in a second pass, reverse each word…

in c#, completely in-place without additional arrays:

static char[] ReverseAllWords(char[] in_text)
{
    int lindex = 0;
    int rindex = in_text.Length - 1;
    if (rindex > 1)
    {
        //reverse complete phrase
        in_text = ReverseString(in_text, 0, rindex);

        //reverse each word in resultant reversed phrase
        for (rindex = 0; rindex <= in_text.Length; rindex++)
        {
            if (rindex == in_text.Length || in_text[rindex] == ' ')
            {
                in_text = ReverseString(in_text, lindex, rindex - 1);
                lindex = rindex + 1;
            }
        }
    }
    return in_text;
}

static char[] ReverseString(char[] intext, int lindex, int rindex)
{
    char tempc;
    while (lindex < rindex)
    {
        tempc = intext[lindex];
        intext[lindex++] = intext[rindex];
        intext[rindex--] = tempc;
    }
    return intext;
}

3

Not exactly in place, but anyway: Python:

>>> a = "These pretzels are making me thirsty"
>>> " ".join(a.split()[::-1])
'thirsty me making are pretzels These'

2

In Smalltalk:

'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]

I know noone cares about Smalltalk, but it’s so beautiful to me.

0

You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered «in place», but it’s not completely «extra data structure free».

Below is code implementing what Bill the Lizard describes:

string words = "this is a test";

// Reverse the entire string
for(int i = 0; i < strlen(words) / 2; ++i) {
  char temp = words[i];
  words[i] = words[strlen(words) - i];
  words[strlen(words) - i] = temp;
}

// Reverse each word
for(int i = 0; i < strlen(words); ++i) {
  int wordstart = -1;
  int wordend = -1;
  if(words[i] != ' ') {
    wordstart = i;
    for(int j = wordstart; j < strlen(words); ++j) {
      if(words[j] == ' ') {
        wordend = j - 1;
        break;
      }
    }
    if(wordend == -1)
      wordend = strlen(words);
    for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
      char temp = words[j];
      words[j] = words[wordend - (j - wordstart)];
      words[wordend - (j - wordstart)] = temp;
    }
    i = wordend;
  }
}

3

What language?
If PHP, you can explode on space, then pass the result to array_reverse.

If its not PHP, you’ll have to do something slightly more complex like:

words = aString.split(" ");
for (i = 0; i < words.length; i++) {
    words[i] = words[words.length-i];
}

2

public static String ReverseString(String str)
{
    int word_length = 0;
    String result = "";
    for (int i=0; i<str.Length; i++)
    {
        if (str[i] == ' ')
        {
            result = " " + result;
            word_length = 0;
        } else 
        {
            result = result.Insert(word_length, str[i].ToString());
            word_length++;
        }
    }
    return result;
}

This is C# code.

0

In Python...

ip = "My name is X Y Z"
words = ip.split()
words.reverse()
print ' '.join(words)

Anyway cookamunga provided good inline solution using python!

1

This is assuming all words are separated by spaces:

#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "What are you looking at";
    int i, n = strlen(string);

    int tail = n-1;
    for(i=n-1;i>=0;i--)
    {
        if(string[i] == ' ' || i == 0)
        {
            int cursor = (i==0? i: i+1);
            while(cursor <= tail)
                printf("%c", string[cursor++]);
            printf(" ");
            tail = i-1;
        }
    }
    return 0;
}

class Program
{
    static void Main(string[] args)
    {
        string s1 =" My Name varma:;
        string[] arr = s1.Split(' ');
        Array.Reverse(arr);
        string str = string.Join(" ", arr);
        Console.WriteLine(str);
        Console.ReadLine();

    }
}

This is not perfect but it works for me right now. I don’t know if it has O(n) running time btw (still studying it ^^) but it uses one additional array to fulfill the task.

It is probably not the best answer to your problem because i use a dest string to save the reversed version instead of replacing each words in the source string. The problem is that i use a local stack variable named buf to copy all the words in and i can not copy but into the source string as this would lead to a crash if the source string is const char * type.

But it was my first attempt to write s.th. like this :) Ok enough blablub. here is code:

#include <iostream>
using namespace std;

void reverse(char *des, char * const s);
int main (int argc, const char * argv[])
{    
    char* s = (char*)"reservered. rights All Saints. The 2011 (c) Copyright 11/10/11 on Pfundstein Markus by Created";
    char *x = (char*)"Dogfish! White-spotted Shark, Bullhead";

    printf("Before: |%s|n", x);
    printf("Before: |%s|n", s);

    char *d = (char*)malloc((strlen(s)+1)*sizeof(char));  
    char *i = (char*)malloc((strlen(x)+1)*sizeof(char));

    reverse(d,s);
    reverse(i,x);

    printf("After: |%s|n", i);
    printf("After: |%s|n", d);

    free (i);
    free (d);

    return 0;
}

void reverse(char *dest, char *const s) {
    // create a temporary pointer
    if (strlen(s)==0) return;
    unsigned long offset = strlen(s)+1;

    char *buf = (char*)malloc((offset)*sizeof(char));
    memset(buf, 0, offset);

    char *p;
    // iterate from end to begin and count how much words we have
    for (unsigned long i = offset; i != 0; i--) {
        p = s+i;
        // if we discover a whitespace we know that we have a whole word
        if (*p == ' ' || *p == '') {
            // we increment the counter
            if (*p != '') {
                // we write the word into the buffer
                ++p;
                int d = (int)(strlen(p)-strlen(buf));
                strncat(buf, p, d);
                strcat(buf, " ");
            }
        }
    }

    // copy the last word
    p -= 1;
    int d = (int)(strlen(p)-strlen(buf));
    strncat(buf, p, d);
    strcat(buf, "");

    // copy stuff to destination string
    for (int i = 0; i < offset; ++i) {
        *(dest+i)=*(buf+i);
    }

    free(buf);
}

We can insert the string in a stack and when we extract the words, they will be in reverse order.

void ReverseWords(char Arr[])
{
    std::stack<std::string> s;
    char *str;
    int length = strlen(Arr);
    str = new char[length+1];
    std::string ReversedArr;
    str = strtok(Arr," ");
    while(str!= NULL)
    {
        s.push(str);
        str = strtok(NULL," ");
    }
    while(!s.empty())
    {
        ReversedArr = s.top();
        cout << " " << ReversedArr;
        s.pop();
    }
}

This quick program works..not checks the corner cases though.

#include <stdio.h>
#include <stdlib.h>
struct node
{
    char word[50];
    struct node *next;
};
struct stack
{
    struct node *top;
};
void print (struct stack *stk);
void func (struct stack **stk, char *str);
main()
{
    struct stack *stk = NULL;
    char string[500] = "the sun is yellow and the sky is blue";
    printf("n%sn", string);
    func (&stk, string);
    print (stk);
}
void func (struct stack **stk, char *str)
{
    char *p1 = str;
    struct node *new = NULL, *list = NULL;
    int i, j;
    if (*stk == NULL)
    {
        *stk = (struct stack*)malloc(sizeof(struct stack));
        if (*stk == NULL)
            printf("n####### stack is not allocated #####n");
        (*stk)->top = NULL;
    }
    i = 0;
    while (*(p1+i) != '')
    {
        if (*(p1+i) != ' ')
        {
            new = (struct node*)malloc(sizeof(struct node));
            if (new == NULL)
                printf("n####### new is not allocated #####n");
            j = 0;
            while (*(p1+i) != ' ' && *(p1+i) != '')
            {
                new->word[j] = *(p1 + i);
                i++;
                j++;
            }
            new->word[j++] = ' ';
            new->word[j] = '';
            new->next = (*stk)->top;
            (*stk)->top = new;
        }
        i++;
   }
}
void print (struct stack *stk)
{
    struct node *tmp = stk->top;
    int i;
    while (tmp != NULL)
    {
        i = 0;
        while (tmp->word[i] != '')
        {
            printf ("%c" , tmp->word[i]);
            i++;
        }
        tmp = tmp->next;
    }
    printf("n");
}

2

Most of these answers fail to account for leading and/or trailing spaces in the input string. Consider the case of str=" Hello world"… The simple algo of reversing the whole string and reversing individual words winds up flipping delimiters resulting in f(str) == "world Hello ".

The OP said «I want to reverse the order of the words» and did not mention that leading and trailing spaces should also be flipped! So, although there are a ton of answers already, I’ll provide a [hopefully] more correct one in C++:

#include <string>
#include <algorithm>

void strReverseWords_inPlace(std::string &str)
{
  const char delim = ' ';
  std::string::iterator w_begin, w_end;
  if (str.size() == 0)
    return;

  w_begin = str.begin();
  w_end   = str.begin();

  while (w_begin != str.end()) {
    if (w_end == str.end() || *w_end == delim) {
      if (w_begin != w_end)
        std::reverse(w_begin, w_end);
      if (w_end == str.end())
        break;
      else
        w_begin = ++w_end;
    } else {
      ++w_end;
    }
  }

  // instead of reversing str.begin() to str.end(), use two iterators that
  // ...represent the *logical* begin and end, ignoring leading/traling delims
  std::string::iterator str_begin = str.begin(), str_end = str.end();
  while (str_begin != str_end && *str_begin == delim)
    ++str_begin;
  --str_end;
  while (str_end != str_begin && *str_end == delim)
    --str_end;
  ++str_end;
  std::reverse(str_begin, str_end);
}

My version of using stack:

public class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        String ns= s.trim();
        Stack<Character> reverse = new Stack<Character>();
        boolean hadspace=false;

        //first pass
        for (int i=0; i< ns.length();i++){
            char c = ns.charAt(i);
            if (c==' '){
                if (!hadspace){
                    reverse.push(c);
                    hadspace=true;
                }
            }else{
                hadspace=false;
                reverse.push(c);
            }
        }
        Stack<Character> t = new Stack<Character>();
        while (!reverse.empty()){
            char temp =reverse.pop();
            if(temp==' '){
                //get the stack content out append to StringBuilder
                while (!t.empty()){
                    char c =t.pop();
                    sb.append(c);
                }
                sb.append(' ');
            }else{
                //push to stack
                t.push(temp);
            }
        }
        while (!t.empty()){
            char c =t.pop();
            sb.append(c);
        }
        return sb.toString();
    }
}

Store Each word as a string in array then print from end

public void rev2() {
    String str = "my name is ABCD";
    String A[] = str.split(" ");

    for (int i = A.length - 1; i >= 0; i--) {
        if (i != 0) {
            System.out.print(A[i] + " ");
        } else {
            System.out.print(A[i]);
        }
    }

}

In Python, if you can’t use [::-1] or reversed(), here is the simple way:

def reverse(text):

  r_text = text.split(" ")
  res = []
  for word in range(len(r_text) - 1, -1, -1): 
    res.append(r_text[word])

  return " ".join(res)

print (reverse("Hello World"))

>> World Hello
[Finished in 0.1s]

Printing words in reverse order of a given statement using C#:

    void ReverseWords(string str)
    {
        int j = 0;
        for (int i = (str.Length - 1); i >= 0; i--)
        {
            if (str[i] == ' ' || i == 0)
            {
                j = i == 0 ? i : i + 1;

                while (j < str.Length && str[j] != ' ')
                    Console.Write(str[j++]);
                Console.Write(' ');
            }
        }
    }

Here is the Java Implementation:

public static String reverseAllWords(String given_string)
{
    if(given_string == null || given_string.isBlank())
        return given_string;

    char[] str = given_string.toCharArray();
    int start = 0;

    // Reverse the entire string
    reverseString(str, start, given_string.length() - 1);

    // Reverse the letters of each individual word
    for(int end = 0; end <= given_string.length(); end++)
    {
        if(end == given_string.length() || str[end] == ' ')
        {
            reverseString(str, start, end-1);
            start = end + 1;
        }
    }
    return new String(str);
}

// In-place reverse string method
public static void reverseString(char[] str, int start, int end)
{
    while(start < end)
    {
        char temp = str[start];
        str[start++] = str[end];
        str[end--] = temp;
    }
}

Actually, the first answer:

words = aString.split(" ");
for (i = 0; i < words.length; i++) {
    words[i] = words[words.length-i];
}

does not work because it undoes in the second half of the loop the work it did in the first half. So, i < words.length/2 would work, but a clearer example is this:

words = aString.split(" "); // make up a list
i = 0; j = words.length - 1; // find the first and last elements
while (i < j) {
    temp = words[i]; words[i] = words[j]; words[j] = temp; //i.e. swap the elements
    i++; 
    j--;
}

Note: I am not familiar with the PHP syntax, and I have guessed incrementer and decrementer syntax since it seems to be similar to Perl.

2

How about …

var words = "My name is X Y Z";
var wr = String.Join( " ", words.Split(' ').Reverse().ToArray() );

I guess that’s not in-line tho.

2

In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).

#include<stdio.h>
#include<stdlib.h>
main(){
  char* a = malloc(1000);
  fscanf(stdin, "%[^n]", a);
  int x = 0, y;
  while(a[x]!='')
  {
    if (a[x]==' ' || a[x]=='n')
    {
      x++;
    }
    else
    {
      y=x;
      while(a[y]!='' && a[y]!=' ' && a[y]!='n')
      { 
        y++;
      }
      int z=y;
      while(x<y)
      {
        y--;
        char c=a[x];a[x]=a[y];a[y]=c; 
        x++;
      }
      x=z;
    }
  }

  fprintf(stdout,a);
  return 0;
}

It can be done more simple using sscanf:

void revertWords(char *s);
void revertString(char *s, int start, int n);
void revertWordsInString(char *s);

void revertString(char *s, int start, int end)
{
     while(start<end)
     {
         char temp = s[start];
         s[start] = s[end];
         s[end]=temp;
         start++;
         end --;
     }
}


void revertWords(char *s)
{
  int start = 0;

  char *temp = (char *)malloc(strlen(s) + 1);
  int numCharacters = 0;
  while(sscanf(&s[start], "%s", temp) !=EOF)
  {
      numCharacters = strlen(temp);

      revertString(s, start, start+numCharacters -1);
      start = start+numCharacters + 1;
      if(s[start-1] == 0)
      return;

  }
  free (temp);

}

void revertWordsInString(char *s)
{
   revertString(s,0, strlen(s)-1);
   revertWords(s);
}

int main()
{
   char *s= new char [strlen("abc deff gh1 jkl")+1];
   strcpy(s,"abc deff gh1 jkl");
   revertWordsInString(s);
   printf("%s",s);
   return 0;
}

import java.util.Scanner;

public class revString {
   static char[] str;

   public static void main(String[] args) {
    //Initialize string
    //str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
    //'r', 'l', 'd' };
    getInput();

    // reverse entire string
    reverse(0, str.length - 1);

    // reverse the words (delimeted by space) back to normal
    int i = 0, j = 0;
    while (j < str.length) {

        if (str[j] == ' ' || j == str.length - 1) {

            int m = i;
            int n;

            //dont include space in the swap. 
            //(special case is end of line)
            if (j == str.length - 1)
                n = j;
            else
                n = j -1;


            //reuse reverse
            reverse(m, n);

            i = j + 1;

        }
        j++;
    }

    displayArray();
}

private static void reverse(int i, int j) {

    while (i < j) {

        char temp;
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;

        i++;
        j--;
    }
}
private static void getInput() {
    System.out.print("Enter string to reverse: ");
    Scanner scan = new Scanner(System.in);
    str = scan.nextLine().trim().toCharArray(); 
}

private static void displayArray() {
    //Print the array
    for (int i = 0; i < str.length; i++) {
        System.out.print(str[i]);
    }
}

}

In Java using an additional String (with StringBuilder):

public static final String reverseWordsWithAdditionalStorage(String string) {
    StringBuilder builder = new StringBuilder();

    char c = 0;
    int index = 0;
    int last = string.length();
    int length = string.length()-1;
    StringBuilder temp = new StringBuilder();
    for (int i=length; i>=0; i--) {
        c = string.charAt(i);
        if (c == SPACE || i==0) {
            index = (i==0)?0:i+1;
            temp.append(string.substring(index, last));
            if (index!=0) temp.append(c);
            builder.append(temp);
            temp.delete(0, temp.length());
            last = i;
        }
    }

    return builder.toString();
}

In Java in-place:

public static final String reverseWordsInPlace(String string) {
    char[] chars = string.toCharArray();

    int lengthI = 0;
    int lastI = 0;
    int lengthJ = 0;
    int lastJ = chars.length-1;

    int i = 0;
    char iChar = 0;
    char jChar = 0;
    while (i<chars.length && i<=lastJ) {
        iChar = chars[i];
        if (iChar == SPACE) {
            lengthI = i-lastI;
            for (int j=lastJ; j>=i; j--) {
                jChar = chars[j];
                if (jChar == SPACE) {
                    lengthJ = lastJ-j;
                    swapWords(lastI, i-1, j+1, lastJ, chars);
                    lastJ = lastJ-lengthI-1;
                    break;
                }
            }
            lastI = lastI+lengthJ+1;
            i = lastI;
        } else {
            i++;
        }
    }

    return String.valueOf(chars);
}

private static final void swapWords(int startA, int endA, int startB, int endB, char[] array) {
    int lengthA = endA-startA+1;
    int lengthB = endB-startB+1;

    int length = lengthA;
    if (lengthA>lengthB) length = lengthB;

    int indexA = 0;
    int indexB = 0;
    char c = 0;
    for (int i=0; i<length; i++) {
        indexA = startA+i;
        indexB = startB+i;

        c = array[indexB];
        array[indexB] = array[indexA];
        array[indexA] = c;
    }

    if (lengthB>lengthA) {
        length = lengthB-lengthA;
        int end = 0;
        for (int i=0; i<length; i++) {
            end = endB-((length-1)-i);
            c = array[end];
            shiftRight(endA+i,end,array);
            array[endA+1+i] = c;
        }
    } else if (lengthA>lengthB) {
        length = lengthA-lengthB;
        for (int i=0; i<length; i++) {
            c = array[endA];
            shiftLeft(endA,endB,array);
            array[endB+i] = c;
        }
    }
}

private static final void shiftRight(int start, int end, char[] array) {
    for (int i=end; i>start; i--) {
        array[i] = array[i-1];
    }
}

private static final void shiftLeft(int start, int end, char[] array) {
    for (int i=start; i<end; i++) {
        array[i] = array[i+1];
    }
}

Here is a C implementation that is doing the word reversing inlace, and it has O(n) complexity.

char* reverse(char *str, char wordend=0)
{
    char c;
    size_t len = 0;
    if (wordend==0) {
        len = strlen(str);
    }
    else {
        for(size_t i=0;str[i]!=wordend && str[i]!=0;i++)
            len = i+1;
    }
            for(size_t i=0;i<len/2;i++) {
                c = str[i];
                str[i] = str[len-i-1];
                str[len-i-1] = c;
            }
    return str;
}

char* inplace_reverse_words(char *w)
{
    reverse(w); // reverse all letters first
    bool is_word_start = (w[0]!=0x20);

    for(size_t i=0;i<strlen(w);i++){
        if(w[i]!=0x20 && is_word_start) {
            reverse(&w[i], 0x20); // reverse one word only
            is_word_start = false;
        }
        if (!is_word_start && w[i]==0x20) // found new word
            is_word_start = true;
    }
    return w;
}

c# solution to reverse words in a sentence

using System;
class helloworld {
    public void ReverseString(String[] words) {
        int end = words.Length-1;
        for (int start = 0; start < end; start++) {
            String tempc;
            if (start < end ) {
                tempc = words[start];
                words[start] = words[end];
                words[end--] = tempc;
            }
        }
        foreach (String s1 in words) {
            Console.Write("{0} ",s1);
        }
    }
}
class reverse {
    static void Main() {
        string s= "beauty lies in the heart of the peaople";
        String[] sent_char=s.Split(' ');
        helloworld h1 = new helloworld();
        h1.ReverseString(sent_char);
    }
}

output:
peaople the of heart the in lies beauty Press any key to continue . . .

0

Better version
Check my blog http://bamaracoulibaly.blogspot.co.uk/2012/04/19-reverse-order-of-words-in-text.html

public string reverseTheWords(string description)
{
    if(!(string.IsNullOrEmpty(description)) && (description.IndexOf(" ") > 1))
    {
        string[] words= description.Split(' ');
        Array.Reverse(words);
        foreach (string word in words)
        {
            string phrase = string.Join(" ", words);
            Console.WriteLine(phrase);
        }
        return phrase;
    }
    return description;
}

public class manip{

public static char[] rev(char[] a,int left,int right) {
    char temp;
    for (int i=0;i<(right - left)/2;i++)    {
        temp = a[i + left];
        a[i + left] = a[right -i -1];
        a[right -i -1] = temp;
    }

    return a;
}
public static void main(String[] args) throws IOException {

    String s= "i think this works";
    char[] str = s.toCharArray();       
    int i=0;
    rev(str,i,s.length());
    int j=0;
    while(j < str.length) {
        if (str[j] != ' ' && j != str.length -1) {
            j++;
        } else
        {
            if (j == (str.length -1))   {
                j++;
            }
            rev(str,i,j);
            i=j+1;
            j=i;
        }
    }
    System.out.println(str);
}

I know there are several correct answers. Here is the one in C that I came up with.
This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.

#include<stdio.h>

char * strRev(char *str, char tok)
{
   int len = 0, i;
   char *temp = str;
   char swap;

   while(*temp != tok && *temp != '') {
      len++; temp++;
   }   
   len--;

   for(i = 0; i < len/2; i++) {
      swap = str[i];
      str[i] = str[len - i]; 
      str[len - i] = swap;
   }   

   // Return pointer to the next token.
   return str + len + 1;
}

int main(void)
{
   char a[] = "Reverse this string.";
   char *temp = a;

   if (a == NULL)
      return -1; 

   // Reverse whole string character by character.
   strRev(a, '');

   // Reverse every word in the string again.
   while(1) {
      temp = strRev(temp, ' ');
      if (*temp == '')
         break;

      temp++;
   }   
   printf("Reversed string: %sn", a); 
   return 0;
}

1

Given a string, the task is to reverse the order of the words in the given string. 

Examples:

Input: s = “geeks quiz practice code” 
Output: s = “code practice quiz geeks”

Input: s = “i love programming very much” 
Output: s = “much very programming love i” 

reverse-words

Approach:

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Follow the below steps to solve the problem:

  • Run a for loop to traverse the string and create a temporary string to store the words
  • If the current character is a space then add the current string to the answer and empty the string
  • Else push the character into the string
  • Print the answer array in reverse order 

Below is the implementation of the above approach: 

C++

#include <bits/stdc++.h>

using namespace std;

void reverseWords(string s)

{

    vector<string> tmp;

    string str = "";

    for (int i = 0; i < s.length(); i++) {

        if (s[i] == ' ') {

            tmp.push_back(str);

            str = "";

        }

        else

            str += s[i];

    }

    tmp.push_back(str);

    int i;

    for (i = tmp.size() - 1; i > 0; i--)

        cout << tmp[i] << " ";

    cout << tmp[0] << endl;

}

int main()

{

    string s = "i like this program very much";

    reverseWords(s);

    return 0;

}

C

#include <stdio.h>

void reverse(char* begin, char* end)

{

    char temp;

    while (begin < end) {

        temp = *begin;

        *begin++ = *end;

        *end-- = temp;

    }

}

void reverseWords(char* s)

{

    char* word_begin = s;

    char* temp = s;

    while (*temp) {

        temp++;

        if (*temp == '') {

            reverse(word_begin, temp - 1);

        }

        else if (*temp == ' ') {

            reverse(word_begin, temp - 1);

            word_begin = temp + 1;

        }

    }

    reverse(s, temp - 1);

}

int main()

{

    char s[] = "i like this program very much";

    char* temp = s;

    reverseWords(s);

    printf("%s", s);

    return 0;

}

Java

import java.util.*;

class GFG {

    static void reverse(char str[], int start, int end)

    {

        char temp;

        while (start <= end) {

            temp = str[start];

            str[start] = str[end];

            str[end] = temp;

            start++;

            end--;

        }

    }

    static char[] reverseWords(char[] s)

    {

        int start = 0;

        for (int end = 0; end < s.length; end++) {

            if (s[end] == ' ') {

                reverse(s, start, end);

                start = end + 1;

            }

        }

        reverse(s, start, s.length - 1);

        reverse(s, 0, s.length - 1);

        return s;

    }

    public static void main(String[] args)

    {

        String s = "i like this program very much ";

        char[] p = reverseWords(s.toCharArray());

        System.out.print(p);

    }

}

Python3

def reverse_word(s, start, end):

    while start < end:

        s[start], s[end] = s[end], s[start]

        start = start + 1

        end -= 1

s = "i like this program very much"

s = list(s)

start = 0

while True:

    try:

        end = s.index(' ', start)

        reverse_word(s, start, end - 1)

        start = end + 1

    except ValueError:

        reverse_word(s, start, len(s) - 1)

        break

s.reverse()

s = "".join(s)

print(s)

C#

using System;

class GFG {

    static void reverse(char[] str, int start, int end)

    {

        char temp;

        while (start <= end) {

            temp = str[start];

            str[start] = str[end];

            str[end] = temp;

            start++;

            end--;

        }

    }

    static char[] reverseWords(char[] s)

    {

        int start = 0;

        for (int end = 0; end < s.Length; end++) {

            if (s[end] == ' ') {

                reverse(s, start, end);

                start = end + 1;

            }

        }

        reverse(s, start, s.Length - 1);

        reverse(s, 0, s.Length - 1);

        return s;

    }

    public static void Main(String[] args)

    {

        String s = "i like this program very much ";

        char[] p = reverseWords(s.ToCharArray());

        Console.Write(p);

    }

}

Javascript

<script>

    function reverse(str,start,end)

    {

        let temp;

        while (start <= end)

        {

            temp = str[start];

            str[start]=str[end];

            str[end]=temp;

            start++;

            end--;

        }

    }

    function reverseWords(s)

    {

        s=s.split("");

        let start = 0;

        for (let end = 0; end < s.length; end++)

        {

            if (s[end] == ' ')

            {

                reverse(s, start, end);

                start = end + 1;

            }

        }

        reverse(s, start, s.length - 1);

        reverse(s, 0, s.length - 1);

        return s.join("");

    }

    var s = "i like this program very much ";

    document.write(reverseWords(s));

</script>

Output

much very program this like i

Time complexity: O(N)
Auxiliary Space: O(N)

Note: The above code doesn’t handle the cases when the string starts with space. 

Below is the implementation of the approach that handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. 

C++

#include <bits/stdc++.h>

using namespace std;

void reverse(string& s, int begin, int end)

{

    while (begin < end) {

        swap(s[begin++], s[end--]);

    }

}

void reverseWords(string& s)

{

    int word_begin = -1;

    int i = 0;

    while (i < s.size()) {

        if ((word_begin == -1) && (s[i] != ' ')) {

            word_begin = i;

        }

        if (word_begin != -1

            && ((s[i + 1] == ' ') || (i + 1 == s.size()))) {

            reverse(s, word_begin, i);

            word_begin = -1;

        }

        i++;

    }

    reverse(s, 0, s.size() - 1);

}

int main()

{

    string s = "i like this program very much";

    reverseWords(s);

    cout << s << endl;

    ;

    return 0;

}

C

#include <stdio.h>

void reverse(char* begin, char* end)

{

    char temp;

    while (begin < end) {

        temp = *begin;

        *begin++ = *end;

        *end-- = temp;

    }

}

void reverseWords(char* s)

{

    char* word_begin = NULL;

    char* temp = s;

    while (*temp) {

        if ((word_begin == NULL) && (*temp != ' ')) {

            word_begin = temp;

        }

        if (word_begin

            && ((*(temp + 1) == ' ')

                || (*(temp + 1) == ''))) {

            reverse(word_begin, temp);

            word_begin = NULL;

        }

        temp++;

    }

    reverse(s, temp - 1);

}

int main()

{

    char s[] = "i like this program very much";

    char* temp = s;

    reverseWords(s);

    printf("%s", s);

    return 0;

}

Java

import java.io.*;

class GFG {

  static void reverse(char[] str, int start, int end)

  {

    char temp;

    while (start <= end) {

      temp = str[start];

      str[start] = str[end];

      str[end] = temp;

      start++;

      end--;

    }

  }

  static char[] reverseWords(char[] s)

  {

    int word_begin = -1;

    int i = 0;

    while (i < s.length) {

      if ((word_begin == -1) && (s[i] != ' ')) {

        word_begin = i;

      }

      if (word_begin != -1

          && ((i + 1 == s.length)

              || (s[i + 1] == ' '))) {

        reverse(s, word_begin, i);

        word_begin = -1;

      }

      i++;

    }

    reverse(s, 0, (s.length - 1));

    return s;

  }

  public static void main(String[] args)

  {

    String s = "i like this program very much";

    char[] p = reverseWords(s.toCharArray());

    System.out.println(p);

  }

}

Python3

def reverse(str, start, end):

    temp = ''

    str1 = ""

    while (start <= end):

        temp = str[start]

        str[start] = str[end]

        str[end] = temp

        start+=1

        end-=1

    return str1.join(str)

def reverseWords(s):

    word_begin = -1

    i = 0

    while (i < len(s)):

        if ((word_begin == -1) and (s[i] != ' ')):

            word_begin = i

        if (word_begin != -1 and ((i + 1 == len(s)) or (s[i + 1] == ' '))):

            s = reverse(list(s), word_begin, i)

            word_begin = -1

        i+=1

    s = reverse(list(s), 0, (len(s) - 1))

    return s

s = "i like this program very much"

p = reverseWords(list(s))

print(p)

C#

using System;

class GFG

{

  static void reverse(char[] str, int start, int end)

  {

    char temp;

    while (start <= end) {

      temp = str[start];

      str[start] = str[end];

      str[end] = temp;

      start++;

      end--;

    }

  }

  static char[] reverseWords(char[] s)

  {

    int word_begin = -1;

    int i = 0;

    while (i < s.Length) {

      if ((word_begin == -1) && (s[i] != ' ')) {

        word_begin = i;

      }

      if (word_begin != -1

          && ((i + 1 == s.Length)

              || (s[i + 1] == ' '))) {

        reverse(s, word_begin, i);

        word_begin = -1;

      }

      i++;

    }

    reverse(s, 0, (s.Length - 1));

    return s;

  }

  static void Main(string[] args)

  {

    String s = "i like this program very much";

    char[] p = reverseWords(s.ToCharArray());

    Console.WriteLine(p);

  }

}

Javascript

function reverse(s, begin, end) {

    while (begin < end) {

        let charArray = [...s];

        let temp = charArray[begin];

        charArray[begin] = charArray[end];

        charArray[end] = temp;

        begin++;

        end--;

        s = charArray.join("");

    }

    return s;

}

function reverseWords(s) {

    let word_begin = -1;

    let i = 0;

    while (i < s.length) {

        if ((word_begin == -1) && (s[i] != ' ')) {

            word_begin = i;

        }

        if (word_begin != -1

            && ((s[i + 1] == ' ') || (i + 1 == s.length))) {

            s = reverse(s, word_begin, i);

            word_begin = -1;

        }

        i++;

    }

    s = reverse(s, 0, s.length - 1);

    return s;

}

let s = "i like this program very much";

s = reverseWords(s);

console.log(s);

Output

much very program this like i

Time Complexity: O(N)
Auxiliary Space: O(N) 

Approach: To solve the problem follow the below idea:

We can do the above task by splitting and saving the string in a reverse manner. 

Follow the below steps to solve the problem:

  • Store the string in the form of words
  • Run a for loop in reverse order to print the words accordingly 

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

int main()

{

    string s[] = { "i",       "like", "this",

                   "program", "very", "much" };

    string ans = "";

    for (int i = 5; i >= 0; i--) {

        ans += s[i] + " ";

    }

    cout << (ans.substr(0, ans.length() - 1)) << endl;

    return 0;

}

Java

public class ReverseWords {

    public static void main(String[] args)

    {

        String s[]

            = "i like this program very much".split(" ");

        String ans = "";

        for (int i = s.length - 1; i >= 0; i--) {

            ans += s[i] + " ";

        }

        System.out.println(

            ans.substring(0, ans.length() - 1));

    }

}

Python3

s = "i like this program very much"

words = s.split(' ')

string = []

for word in words:

    string.insert(0, word)

print(" ".join(string))

C#

using System;

public class ReverseWords {

    public static void Main()

    {

        string[] s

            = "i like this program very much".Split(' ');

        string ans = "";

        for (int i = s.Length - 1; i >= 0; i--) {

            ans += s[i] + " ";

        }

        Console.Write(ans.Substring(0, ans.Length - 1));

    }

}

Javascript

<script>

var s= ["i", "like", "this", "program", "very", "much"];

    var ans ="";

    for (var i = 5; i >= 0; i--)

    {

        ans += s[i] + " ";

    }

    document.write(ans.slice(0,ans.length-1));

</script>

Output

much very program this like i

Time Complexity: O(N)
Auxiliary Space: O(N) 

Reverse words in a given string using the swap operation:

The above task can also be accomplished by splitting the words separately and directly swapping the string starting from the middle.

Follow the below steps to solve the problem:

  • Store the string in the form of words
  • Swap the words with each other starting from the middle
  • Print the string

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

string RevString(string s[], int l)

{

    if (l % 2 == 0) {

        int j = l / 2;

        while (j <= l - 1) {

            string temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    else {

        int j = (l / 2) + 1;

        while (j <= l - 1) {

            string temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    string S = s[0];

    for (int i = 1; i < 6; i++) {

        S = S + " " + s[i];

    }

    return S;

}

int main()

{

    string s = "i like this program very much";

    string words[]

        = { "i", "like", "this", "program", "very", "much" };

    cout << RevString(words, 6) << endl;

    return 0;

}

Java

import java.io.*;

class GFG {

    public static String[] RevString(String[] s, int l)

    {

        if (l % 2 == 0) {

            int j = l / 2;

            while (j <= l - 1) {

                String temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        else {

            int j = (l / 2) + 1;

            while (j <= l - 1) {

                String temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        return s;

    }

    public static void main(String[] args)

    {

        String s = "i like this program very much";

        String[] words = s.split("\s");

        words = RevString(words, words.length);

        s = String.join(" ", words);

        System.out.println(s);

    }

}

Python3

def RevString(s, l):

    if l % 2 == 0:

        j = int(l/2)

        while(j <= l - 1):

            s[j], s[l - j - 1] = s[l - j - 1], s[j]

            j += 1

    else:

        j = int(l/2 + 1)

        while(j <= l - 1):

            s[j], s[l - 1 - j] = s[l - j - 1], s[j]

            j += 1

        return s

s = 'i like this program very much '

string = s.split(' ')

string = RevString(string, len(string))

print(" ".join(string))

C#

using System;

class GFG {

    static string RevString(string[] s, int l)

    {

        if (l % 2 == 0) {

            int j = l / 2;

            while (j <= l - 1) {

                string temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        else {

            int j = (l / 2) + 1;

            while (j <= l - 1) {

                string temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        string S = s[0];

        for (int i = 1; i < 6; i++) {

            S = S + " " + s[i];

        }

        return S;

    }

    public static void Main()

    {

        string[] words

            = {  "i", "like", "this", "program", "very", "much" };

        string a = RevString(words, words.Length);

        Console.WriteLine(a);

    }

}

Javascript

<script>

function RevString(s, l)

{

    if (l % 2 == 0)

    {

        let j = parseInt(l / 2, 10);

        while (j <= l - 1)

        {

            let temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    else

    {

        let j = parseInt((l / 2), 10) + 1;

        while (j <= l - 1)

        {

            let temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    let S = s[0];

    for(let i = 1; i < 9; i++)

    {

        S = S + " " + s[i];

    }

    return S;

}

let s = "i like this program very much";

let words = [  "i", "like", "this", "program", "very much"];

document.write(RevString(words, 9));

</script>

Output

much very program this like i

Time complexity: O(N)
Auxiliary Space: O(N)

Reverse words in a given string using constant space:

Follow the below steps to solve the problem:

  • Go through the string and mirror each word in the string, 
  • Then, in the end, mirror the whole string.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

string reverse_words(string s)

{

    int left = 0, i = 0, n = s.size();

    while (s[i] == ' ')

        i++;

    left = i;

    while (i < n) {

        if (i + 1 == n || s[i] == ' ') {

            int j = i - 1;

            if (i + 1 == n)

                j++;

            while (left < j)

                swap(s[left++], s[j--]);

            left = i + 1;

        }

        if (i > left && s[left] == ' ')

            left = i;

        i++;

    }

    reverse(s.begin(), s.end());

    return s;

}

int main()

{

    string str = "i like this program very much";

    str = reverse_words(str);

    cout << str;

    return 0;

}

Java

import java.io.*;

class GFG {

    public static String swap(String str, int i, int j)

    {

        char ch[] = str.toCharArray();

        char temp = ch[i];

        ch[i] = ch[j];

        ch[j] = temp;

        return new String(ch);

    }

    public static String reverse_words(String s)

    {

        int left = 0, i = 0, n = s.length();

        while (s.charAt(i) == ' ')

            i++;

        left = i;

        while (i < n) {

            if (i + 1 == n || s.charAt(i) == ' ') {

                int j = i - 1;

                if (i + 1 == n)

                    j++;

                while (left < j)

                    s = swap(s, left++, j--);

                left = i + 1;

            }

            if (i > left && s.charAt(left) == ' ')

                left = i;

            i++;

        }

        s = new StringBuilder(s).reverse().toString();

        return s;

    }

    public static void main(String[] args)

    {

        String str

            = "i like this program very much";

        str = reverse_words(str);

        System.out.println(str);

    }

}

Python3

def reverse_words(s):

    left = 0

    i = 0

    s = list(s)

    n = len(s)

    while(s[i] == ' '):

        i = i+1

    left = i

    while(i < n):

        if(i+1 == n or s[i] == ' '):

            j = i-1

            if i+1 == n:

                j = j+1

            while left < j:

                s[left], s[j] = s[j], s[left]

                left = left+1

                j = j-1

            left = i + 1

        if(i > left and s[left] == ' '):

            left = i

        i = i+1

    s = ''.join(s)

    s = s[::-1]

    return s

s1 = "i like this program very much"

s1 = reverse_words(s1)

print(s1)

C#

using System;

class GFG {

    public static string swap(string str, int i, int j)

    {

        char[] ch = str.ToCharArray();

        char temp = ch[i];

        ch[i] = ch[j];

        ch[j] = temp;

        return new String(ch);

    }

    public static string reverse_words(string s)

    {

        int left = 0, i = 0, n = s.Length;

        while (s[i] == ' ')

            i++;

        left = i;

        while (i < n) {

            if (i + 1 == n || s[i] == ' ') {

                int j = i - 1;

                if (i + 1 == n)

                    j++;

                while (left < j)

                    s = swap(s, left++, j--);

                left = i + 1;

            }

            if (i > left && s[left] == ' ')

                left = i;

            i++;

        }

        char[] charArray = s.ToCharArray();

        Array.Reverse(charArray);

        return new string(charArray);

    }

    public static void Main(string[] args)

    {

        string str = "i like this program very much";

        str = reverse_words(str);

        Console.WriteLine(str);

    }

}

Javascript

function swap(s,a,b)

{

    let charArray = [...s];

    let temp = s[a];

    charArray[a] = s[b];

    charArray[b] = temp;

    return charArray.join("");

}

function reverse(str) {

    let charArray = [...str];

    let ans = "";

    for(let i=charArray.length-1;i>=0;i--)

    {

        ans+=charArray[i];

    }

    return ans;

 }

function reverse_words(s)

{

    let left = 0, i = 0, n = s.length;

    while (s[i] == ' ')

        i++;

    left = i;

    while (i < n) {

        if (i + 1 == n || s[i] == ' ') {

            let j = i - 1;

            if (i + 1 == n)

                j++;

            while (left < j)

            {

                s = swap(s,left++, j--);

            }

            left = i + 1;

        }

        if (i > left && s[left] == ' ')

            left = i;

        i++;

    }

    s = reverse(s);

    return s;

}

let str = "i like this program very much";

str = reverse_words(str);

console.log(str);

Output

much very program this like i

Time complexity: O(N)
Auxiliary Space: O(1)

Reverse words in a given string using constant space: using the slicing method and join functions:

Below is the implementation of the above approach:

Java

import java.util.*;

class GFG {

    public static void main(String[] args)

    {

        String text

            = "i like this program very much";

        String str[] = text.split(" ");

        Collections.reverse(Arrays.asList(str));

        System.out.println(String.join(" ", str));

    }

}

Python3

string = "i like this program very much"

s = string.split()[::-1]

print(" ".join(s))

PHP

<?php

$string = "i like this program very much";

$array = explode(" ", $string);

$rarray = array_reverse($array);

echo $newstring = implode(" ", $rarray);

?>

C#

using System;

using System.Linq;

public class GFG {

    static public void Main()

    {

        string text

            = "i like this program very much";

        Console.WriteLine(

            string.Join(" ", text.Split(' ').Reverse()));

    }

}

Javascript

        let text= "i like this program very much";

        let str = text.split(" ");

        str.reverse();

        str = str.join(" ");

        console.log(str);

C++

#include<bits/stdc++.h>

using namespace std;

int main() {

    string text = "i like this program very much";

    vector<string> str;

    istringstream iss(text);

    for (string s; iss >> s;) {

        str.push_back(s);

    }

    reverse(str.begin(), str.end());

    cout << str[0];

    for (int i = 1; i < str.size(); i++) {

        cout << " " << str[i];

    }

    return 0;

}

Output

much very program this like i

Time complexity: O(N2)
Auxiliary Space: O(N)

Approach: Without splitting the string

By this approach, we can even remove extra trailing spaces and in between the words also.

Basically, this algorithm involves 3 steps.

If you find white space, there can be two possibilities. 
It might be end of a word or else extra trailing space in between the words.
if it is not a white space, add the character to temporary word as shown in the below code.

Java

import java.util.*;

class GFG {

    public static String reverseString(String s)

    {

        StringBuilder ans=new StringBuilder();

        String temp = "";

        for(int i=0;i<s.length();i++)

        {

            char ch = s.charAt(i);

            if(ch==' ')

            {

                if(!temp.equals(""))

                {

                    ans.insert(0,temp+" ");

                }

                temp = "";

            }

            else

                temp += ch;

        }

        return ans.toString().substring(0,ans.length()-1);

    }

    public static void main(String[] args) {

        String s1=" Welcome to Geeks For Geeks ";

        System.out.println("Before reversing length of string : "+s1.length());

        String ans1=reverseString(s1);

        System.out.println("After reversing length of string : "+ans1.length());

        System.out.println("""+ans1+""n");

        String s2=" I Love Java   Programming     ";

        System.out.println("Before reversing length of string : "+s2.length());

        String ans2=reverseString(s2);

        System.out.println("After reversing length of string : "+ans2.length());

        System.out.println("""+ans2+""");

    }

}

Output

Before reversing length of string : 28
After reversing length of string : 26
"Geeks For Geeks to Welcome"

Before reversing length of string : 28
After reversing length of string : 24
"Programming     Java Love I"

Time Complexity: O(N) where N is length of string

Auxiliary Space: O(1) 

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

#include <iostream>

#include <algorithm>

using namespace std;

int main() {

string str = «you shall not pass»;

cout << «Original string: » << str << endl;

// Use the built-in reverse to get char-by-char reversal.

reverse(str.begin(), str.end());

string buffer = «»;

string ans = «»;

// This for loop then reverses each individual

// word in the string.

for (int i=0; i < str.length(); i++)

{

if (str[i] != ‘ ‘)

{

buffer += str[i];

}

else

{

reverse(buffer.begin(), buffer.end());

ans += buffer + » «;

buffer = «»;

}

}

// Reversing the last word in the string outside the loop:

reverse(buffer.begin(), buffer.end());

ans += buffer;

cout << «Reversed string: » << ans << endl;

}

Overview

In this problem «Reverse words in a String», we are given an input string s. We need to reverse the order of the words and return a string of the words in reverse order.

Scope

This article tells how to reverse words in a string.
In this article we will learn Splitting and Saving the String in a Reverse Manner approach.
In this article we will learn to reverse words in a string Using the Two-Pointers Approach.

Takeaways

In this article we will learn how to reverse words in a string using different approach.

Example

Input :

s = "welcome to scaler topics"

Output :

"topics scaler to welcome"

Example Explanation

The string given to us is «welcome to scaler topics». To reverse the words of this string, we need to think of a logic to reverse the words and also to remove any leading or trailing spaces. This gives us «topics scaler to welcome».

Constraints

  • Length of the string s will be between 1 and 104.
  • s could contain English letters (upper-case and lower-case), digits, and spaces ‘ ‘.
  • There is at least one word in s.

Approach 1 : Splitting and Saving the String in a Reverse Manner

One of the easiest ways to reverse words in a string is by splitting the string and then saving it in reverse order. This is the naive approach. We will now look at the code for this method :

Java Implementation

In Java, we have the split method, which helps us split the string. We use it to split the string using the delimiter and reverse and store the line in another variable.

public class Scaler {
     public static void main(String[] args) {
        String input = "hello world";
        String s[] = input.split(" ");
        String res = "";
        for (int i = s.length - 1; i >= 0; i--) {
            res += s[i] + " ";
        }

        System.out.println(res.substring(0, res.length() - 1));
    }
}

Output :


Python Implementation

In python too, we have the split method, which helps us split the string. We use it to split the string using the delimiter and reverse and store the line in another variable.

s = "hello world"
words = s.split(' ')
res =[]
for word in words:
    res.insert(0, word)

print(" ".join(res))

Output :


C++ Implementation

#include <iostream>
using namespace std;

string reverseWords(string s) {
    string word = "";
    string res = "";
    for (char i: s) {
        if (i == ' ') {
            res = word + " " + res;
            word = "";
        } else {
            word += i;
        }
    }
    res = word + " " + res;
 return res.substr(0, res.size() - 1);
}

int main() {
	string input = "hello world";
	string res = reverseWords(input);
	cout << res;
	return 0;
}

Output :


Complexity Analysis

Let’s analyze the time and space complexity of this approach :

Time Complexity : O(n)O(n) as we use only one for a loop.
Space Complexity : O(n)O(n) as we are storing our output that is, the reversed string in a new variable.

Approach 2 : Using the Two-Pointers Approach

Now, here comes the optimal solution for this problem.

We initialize two pointers, one at the start of the string and another at the end. Then, we swap the words from the start and end, to achieve the reversed string.

Algorithm :

  1. Turn the string s into an array of strings in which the words of s are stored.
  2. Now, initialise the left and right pointers at 0 and s.length()s.length()11.
  3. Now, we need to swap the elements at the left and right pointers. For that, move the left pointer ahead and the right pointer backward by one position and swap the elements at each position while the left pointer does not exceed the right pointer.
  4. Return the final string.

Java Implementation

import java.util.*;

public class Scaler {

    public static String Reverse(String[] words) {
        int left = 0, right = words.length - 1;
        while (left <= right) {
            String temp = words[left];
            words[left] = words[right];
            words[right] = temp;
            left += 1;
            right -= 1;
        }
        String res = String.join(" ", words);
        return res;
    }

    public static void main(String[] args) {
        String s = "welcome reader";
        String[] words = s.split("\s").trim();
        String res = Reverse(words);
        System.out.println(res);
    }
}

Output :


Python Implementation

s = "welcome reader"
s = s.split(" ")
left = 0
right = len(s) - 1
while left <= right:
    s[left], s[right] = s[right], s[left]
    left += 1
    right -= 1
res = " ".join(s)
print(res)

Output :


C++ Implementation

#include <iostream>
#include <vector>
using namespace std;

 string reverseWords(string s) {
  vector < string > words;
  string str = "";
  for (char c: s) {
    if (c == ' ') {
      words.push_back(str);
      str = "";
    } else {
      str += c;
    }
  }
  words.push_back(str);
  int left = 0, right = words.size() - 1;
  while (left <= right) {
    swap(words[left], words[right]);
    left++;
    right--;
  }
  string res = "";
  for (auto x: words) {
    res += x;
    res += " ";
  }
  res.pop_back();
  return res;
}

int main() {
	string input = "hello world";
	string res = reverseWords(input);
	cout << res;
	return 0;
}

Output :


Complexity Analysis

Let’s analyze the time and space complexity of this approach :

Time Complexity : O(n)O(n)
Space Complexity : O(1)O(1)

Conclusion

  • Reverse words in a string is a really important problem regarding interview preparation.
  • One of the easiest ways to solve this problem is by splitting the string and then saving it in reverse order.
  • Another way is to swap the words from the start and end to achieve the reversed string. This is also the optimal solution to the problem.

Task

Reverse words in a string
You are encouraged to solve this task according to the task description, using any language you may know.

Task

Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified.

Example

Hey you, Bub!   would be shown reversed as:   Bub! you, Hey

Tokens are any non-space characters separated by spaces (formally, white-space);   the visible punctuation form part of the word within which it is located and should not be modified.

You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space.

Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result.

Display the strings in order   (1st, 2nd, 3rd, ···),   and one string per line.

(You can consider the ten strings as ten lines, and the tokens as words.)

Input data
             (ten lines within the box)
 line
     ╔════════════════════════════════════════╗
   1 ║  ---------- Ice and Fire ------------  ║
   2 ║                                        ║  ◄─── a blank line here.
   3 ║  fire, in end will world the say Some  ║
   4 ║  ice. in say Some                      ║
   5 ║  desire of tasted I've what From       ║
   6 ║  fire. favor who those with hold I     ║
   7 ║                                        ║  ◄─── a blank line here.
   8 ║  ... elided paragraph last ...         ║
   9 ║                                        ║  ◄─── a blank line here.
  10 ║  Frost Robert -----------------------  ║
     ╚════════════════════════════════════════╝
Cf.
  • Phrase reversals

11l[edit]

Translation of: Python

V text =
‘---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------’

L(line) text.split("n")
   print(reversed(line.split(‘ ’)).join(‘ ’))
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Action![edit]

PROC Reverse(CHAR ARRAY src,dst)
  BYTE i,j,k,beg,end

  i=1 j=src(0)
  WHILE j>0
  DO
    WHILE j>0 AND src(j)=$20
    DO j==-1 OD
    IF j=0 THEN
      EXIT
    ELSE
      end=j
    FI
    
    WHILE j>0 AND src(j)#$20
    DO j==-1 OD
    beg=j+1

    IF i>1 THEN
      dst(i)=$20 i==+1
    FI

    FOR k=beg TO end
    DO
      dst(i)=src(k) i==+1
    OD
  OD
  dst(0)=i-1
RETURN

PROC Test(CHAR ARRAY src)
  CHAR ARRAY dst(40)

  Reverse(src,dst)
  PrintE(dst)
RETURN

PROC Main()
  Test("---------- Ice and Fire ------------")
  Test("")
  Test("fire, in end will world the say Some")
  Test("ice. in say Some")
  Test("desire of tasted I've what From")
  Test("fire. favor who those with hold I")
  Test("")
  Test("... elided paragraph last ...")
  Test("")
  Test("Frost Robert -----------------------")
RETURN

Screenshot from Atari 8-bit computer

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Ada[edit]

Simple_Parse[edit]

To Split a string into words, we define a Package «Simple_Parse». This package is also used for the Phrase Reversal Task [[1]].

package Simple_Parse is
   -- a very simplistic parser, useful to split a string into words
   
   function Next_Word(S: String; Point: in out Positive) 
		     return String;
   -- a "word" is a sequence of non-space characters
   -- if S(Point .. S'Last) holds at least one word W
   -- then  Next_Word increments Point by len(W) and returns W. 
   -- else  Next_Word sets Point to S'Last+1 and returns ""
      
end Simple_Parse;

The implementation of «Simple_Parse»:

package body Simple_Parse is
   
   function Next_Word(S: String; Point: in out Positive) return String is
      Start: Positive := Point;
      Stop: Natural;
   begin
      while Start <= S'Last and then S(Start) = ' ' loop
	 Start := Start + 1;
      end loop; -- now S(Start) is the first non-space, 
		-- or Start = S'Last+1 if S is empty or space-only
      Stop := Start-1; -- now S(Start .. Stop) = ""
      while Stop < S'Last and then S(Stop+1) /= ' ' loop
	 Stop := Stop + 1;
      end loop; -- now S(Stop+1) is the first sopace after Start
		-- or Stop = S'Last if there is no such space
      Point := Stop+1;
      return S(Start .. Stop);
   end Next_Word;
      
end Simple_Parse;

Main Program[edit]

with Ada.Text_IO, Simple_Parse; 

procedure Reverse_Words is
   
   function Reverse_Words(S: String) return String is
      Cursor: Positive := S'First;
      Word: String := Simple_Parse.Next_Word(S, Cursor);
   begin
      if Word = "" then 
         return "";
      else
         return Reverse_Words(S(Cursor .. S'Last)) & " " & Word;
      end if;
   end Reverse_Words;
   
   use Ada.Text_IO;
begin
   while not End_Of_File loop
      Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input
   end loop;
end Reverse_Words;

Aime[edit]

integer j;
list l, x;
text s, t;

l = list("---------- Ice and Fire ------------",
         "",
         "fire, in end will world the say Some",
         "ice. in say Some",
         "desire of tasted I've what From",
         "fire. favor who those with hold I",
         "",
         "... elided paragraph last ...",
         "",
         "Frost Robert -----------------------");

for (, t in l) {
    file().b_affix(t).list(x, 0);
    for (j, s in x.reverse) {
        o_space(sign(j));
        o_text(s);
    }
    o_newline();
}
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

ALGOL 68[edit]

# returns original phrase with the order of the words reversed #
# a word is a sequence of non-blank characters                 #
PROC reverse word order = ( STRING original phrase )STRING:
     BEGIN
        STRING words reversed := "";
        STRING separator      := "";
        INT    start pos      := LWB original phrase;
        WHILE
            # skip leading spaces #
            WHILE IF start pos <= UPB original phrase
                  THEN original phrase[ start pos ] = " "
                  ELSE FALSE
                  FI
            DO start pos +:= 1
            OD;
            start pos <= UPB original phrase
        DO
            # have another word, find it #
            INT end pos := start pos;
            WHILE IF end pos <= UPB original phrase
                  THEN original phrase[ end pos ] /= " "
                  ELSE FALSE
                  FI
            DO end pos +:= 1
            OD;
            ( original phrase[ start pos : end pos - 1 ] + separator ) +=: words reversed;
            separator := " ";
            start pos := end pos + 1
        OD;
        words reversed
     END # reverse word order # ;
 
# reverse the words in the lines as per the task #
print( ( reverse word order ( "--------- Ice and Fire ------------ " ), newline ) );
print( ( reverse word order ( "                                    " ), newline ) );
print( ( reverse word order ( "fire, in end will world the say Some" ), newline ) );
print( ( reverse word order ( "ice. in say Some                    " ), newline ) );
print( ( reverse word order ( "desire of tasted I've what From     " ), newline ) );
print( ( reverse word order ( "fire. favor who those with hold I   " ), newline ) );
print( ( reverse word order ( "                                    " ), newline ) );
print( ( reverse word order ( "... elided paragraph last ...       " ), newline ) );
print( ( reverse word order ( "                                    " ), newline ) );
print( ( reverse word order ( "Frost Robert -----------------------" ), newline ) )
------------ Fire and Ice ---------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

AppleScript[edit]

on run

    unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------")))

end run


-- GENERIC FUNCTIONS ---------------------------------------------------------

-- reverseWords :: String -> String
on reverseWords(str)
    unwords(|reverse|(|words|(str)))
end reverseWords

-- |reverse| :: [a] -> [a]
on |reverse|(xs)
    if class of xs is text then
        (reverse of characters of xs) as text
    else
        reverse of xs
    end if
end |reverse|

-- |lines| :: Text -> [Text]
on |lines|(str)
    splitOn(linefeed, str)
end |lines|

-- |words| :: Text -> [Text]
on |words|(str)
    splitOn(space, str)
end |words|

-- ulines :: [Text] -> Text
on unlines(lstLines)
    intercalate(linefeed, lstLines)
end unlines

-- unwords :: [Text] -> Text
on unwords(lstWords)
    intercalate(space, lstWords)
end unwords

-- splitOn :: Text -> Text -> [Text]
on splitOn(strDelim, strMain)
    set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
    set lstParts to text items of strMain
    set my text item delimiters to dlm
    lstParts
end splitOn

-- interCalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    strJoined
end intercalate

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to lambda(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property lambda : f
        end script
    end if
end mReturn
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Applesoft BASIC[edit]

100 DATA"---------- ICE AND FIRE ------------"
110 DATA"                                    "
120 DATA"FIRE, IN END WILL WORLD THE SAY SOME"
130 DATA"ICE. IN SAY SOME                    "
140 DATA"DESIRE OF TASTED I'VE WHAT FROM     "
150 DATA"FIRE. FAVOR WHO THOSE WITH HOLD I   "
160 DATA"                                    "
170 DATA"... ELIDED PARAGRAPH LAST ...       "
180 DATA"                                    "
190 DATA"FROST ROBERT -----------------------"

200 FOR L = 1 TO 10
210     READ T$
220     I = LEN(T$)
240     IF I THEN GOSUB 300 : PRINT W$; : IF I THEN PRINT " "; : GOTO 240
250     PRINT
260 NEXT L
270 END

300 W$ = ""
310 FOR I = I TO 1 STEP -1
320     IF MID$(T$, I, 1) = " " THEN NEXT I : RETURN
330 FOR I = I TO 1 STEP -1
340     C$ = MID$(T$, I, 1)
350     IF C$ <> " " THEN  W$ = C$ + W$ : NEXT I
360 RETURN

Arturo[edit]

text: {
---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------}

reversed: map split.lines text =>
    [join.with:" " reverse split.words &]

print join.with:"n" reversed
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

AutoHotkey[edit]

Data := "
(Join`r`n
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert ----------------------- 
)"

Loop, Parse, Data, `n, `r
{
	Loop, Parse, A_LoopField, % A_Space
		Line := A_LoopField " " Line
	Output .= Line "`n", Line := ""
}
MsgBox, % RTrim(Output, "`n")

AWK[edit]

# syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
BEGIN {
    text[++i] = "---------- Ice and Fire ------------"
    text[++i] = ""
    text[++i] = "fire, in end will world the say Some"
    text[++i] = "ice. in say Some"
    text[++i] = "desire of tasted I've what From"
    text[++i] = "fire. favor who those with hold I"
    text[++i] = ""
    text[++i] = "... elided paragraph last ..."
    text[++i] = ""
    text[++i] = "Frost Robert -----------------------"
    leng = i
    for (i=1; i<=leng; i++) {
      n = split(text[i],arr," ")
      for (j=n; j>0; j--) {
        printf("%s ",arr[j])
      }
      printf("n")
    }
    exit(0)
}
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

BaCon[edit]

PRINT REV$("---------- Ice and Fire ------------")
PRINT
PRINT REV$("fire, in end will world the say Some")
PRINT REV$("ice. in say Some                    ")
PRINT REV$("desire of tasted I've what From     ")
PRINT REV$("fire. favor who those with hold I   ")
PRINT
PRINT REV$("... elided paragraph last ...       ")
PRINT
PRINT REV$("Frost Robert -----------------------")

Using the REV$ function which takes a sentence as a delimited string where the items are separated by a delimiter (the space character is the default delimiter).

------------ Fire and Ice ----------

Some say the world will end in fire,
                    Some say in ice.
     From what I've tasted of desire
   I hold with those who favor fire.

       ... last paragraph elided ...

----------------------- Robert Frost

Batch File[edit]

@echo off

::The Main Thing...
cls
echo.
call :reverse "---------- Ice and Fire ------------"
call :reverse
call :reverse "fire, in end will world the say Some"
call :reverse "ice. in say Some"
call :reverse "desire of tasted I've what From"
call :reverse "fire. favor who those with hold I"
call :reverse
call :reverse "... elided paragraph last ..."
call :reverse
call :reverse "Frost Robert -----------------------" 
echo.
pause>nul
exit
::/The Main Thing...

::The Function...
:reverse
set reversed=&set word=&set str=%1
:process
for /f "tokens=1,*" %%A in (%str%) do (
	set str=%%B
	set word=%%A
)
set reversed=%word% %reversed%
set str="%str%"
if not %str%=="" goto process

echo.%reversed%
goto :EOF
::/The Function...
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

BASIC256[edit]

Translation of: FreeBASIC

source = freefile
open (source, "m:text.txt")
textEnt$ = ""
dim textSal$(size(source)*8)
linea = 0

while not eof(source)
	textEnt$ = readline(source)
	linea += 1
	textSal$[linea] = textEnt$
end while

for n = size(source) to 1 step -1
	print textSal$[n];
next n
close source

BBC BASIC[edit]

      PRINT FNreverse("---------- Ice and Fire ------------")
          'FNreverse("")
          'FNreverse("fire, in end will world the say Some")
          'FNreverse("ice. in say Some")
          'FNreverse("desire of tasted I've what From")
          'FNreverse("fire. favor who those with hold I")
          'FNreverse("")
          'FNreverse("... elided paragraph last ...")
          'FNreverse("")
          'FNreverse("Frost Robert -----------------------")
      END

      DEF FNreverse(s$)
      LOCAL sp%
      sp%=INSTR(s$," ")
      IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Bracmat[edit]

("---------- Ice and Fire ------------
                                    
fire, in end will world the say Some
ice. in say Some                    
desire of tasted I've what From     
fire. favor who those with hold I   
                                    
... elided paragraph last ...       
                                    
Frost Robert -----------------------"
  : ?text
& ( reverse
  =   token tokens reversed
    .   :?tokens
      &   whl
        ' ( @( !arg
             : ?token (" "|t|r) ?arg
             )
          & !tokens !token:?tokens
          )
      & !tokens !arg:?tokens
      & :?reversed
      &   whl
        ' ( !tokens:%?token %?tokens
          & " " !token !reversed:?reversed
          )
      & !tokens !reversed:?reversed
      & str$!reversed
  )
& :?output
&   whl
  ' ( @(!text:?line n ?text)
    & !output reverse$!line n:?output
    )
& !output reverse$!text:?output
& out$str$!output
);
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Burlesque[edit]

blsq ) "It is not raining"wd<-wd
"raining not is It"
blsq ) "ice. in say some"wd<-wd
"some say in ice."

C[edit]

#include <stdio.h>
#include <ctype.h>

void rev_print(char *s, int n)
{
        for (; *s && isspace(*s); s++);
        if (*s) {
                char *e;
                for (e = s; *e && !isspace(*e); e++);
                rev_print(e, 0);
                printf("%.*s%s", (int)(e - s), s, " " + n);
        }
        if (n) putchar('n');
}

int main(void)
{
        char *s[] = {
                "---------- Ice and Fire ------------",
                "                                    ",
                "fire, in end will world the say Some",
                "ice. in say Some                    ",
                "desire of tasted I've what From     ",
                "fire. favor who those with hold I   ",
                "                                    ",
                "... elided paragraph last ...       ",
                "                                    ",
                "Frost Robert -----------------------",
                0
        };
        int i;
        for (i = 0; s[i]; i++) rev_print(s[i], 1);

        return 0;
}

Output is the same as everyone else’s.

C#[edit]

using System;

public class ReverseWordsInString
{
    public static void Main(string[] args)
    {
        string text = @"
            ---------- Ice and Fire ------------

            fire, in end will world the say Some
            ice. in say Some
            desire of tasted I've what From
            fire. favor who those with hold I

            ... elided paragraph last ...

            Frost Robert -----------------------
            ";

        foreach (string line in text.Split(Environment.NewLine)) {
            //Splits on any whitespace, not just spaces
            string[] words = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
            Array.Reverse(words);
            WriteLine(string.Join(" ", words));
        }
    }
}

C++[edit]

#include <algorithm>
#include <functional>
#include <string>
#include <iostream>
#include <vector>

//code for a C++11 compliant compiler
template <class BidirectionalIterator, class T>
void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
   std::reverse(first, last);
   auto block_last = first;
   do {
      using std::placeholders::_1;
      auto block_first = std::find_if_not(block_last, last, 
         std::bind(std::equal_to<T>(),_1, separator));
      block_last = std::find(block_first, last, separator);
      std::reverse(block_first, block_last);
   } while(block_last != last);
}

//code for a C++03 compliant compiler
template <class BidirectionalIterator, class T>
void block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
   std::reverse(first, last);
   BidirectionalIterator block_last = first;
   do {
      BidirectionalIterator block_first = std::find_if(block_last, last, 
         std::bind2nd(std::not_equal_to<T>(), separator));
      block_last = std::find(block_first, last, separator);
      std::reverse(block_first, block_last);
   } while(block_last != last);
}

int main() {
   std::string str1[] = 
    {
        "---------- Ice and Fire ------------",
        "",
        "fire, in end will world the say Some",
        "ice. in say Some",
        "desire of tasted I've what From",
        "fire. favor who those with hold I",
        "",
        "... elided paragraph last ...",
        "",
        "Frost Robert -----------------------"
    };

   std::for_each(begin(str1), end(str1), [](std::string& s){
      block_reverse_cpp11(begin(s), end(s), ' ');
      std::cout << s << std::endl;
   });
   
   std::for_each(begin(str1), end(str1), [](std::string& s){
      block_reverse_cpp03(begin(s), end(s), ' ');
      std::cout << s << std::endl;
   });

   return 0;
}

Alternate version[edit]

#include <string>
#include <iostream>
using namespace std;
 
string invertString( string s )
{
    string st, tmp;
    for( string::iterator it = s.begin(); it != s.end(); it++ )
    {
        if( *it != 32 ) tmp += *it;
        else
        {
            st = " " + tmp + st;
            tmp.clear();
        }
    }
    return tmp + st;
}
 
int main( int argc, char* argv[] )
{
    string str[] = 
    {
        "---------- Ice and Fire ------------",
        "",
        "fire, in end will world the say Some",
        "ice. in say Some",
        "desire of tasted I've what From",
        "fire. favor who those with hold I",
        "",
        "... elided paragraph last ...",
        "",
        "Frost Robert -----------------------"
    };
    for( int i = 0; i < 10; i++ )
        cout << invertString( str[i] ) << "n";
 
    cout << "n";
    return system( "pause" );
}

Clojure[edit]

(def poem 
  "---------- Ice and Fire ------------
 
   fire, in end will world the say Some
   ice. in say Some 
   desire of tasted I've what From
   fire. favor who those with hold I
 
   ... elided paragraph last ...
 
   Frost Robert -----------------------")

(dorun
  (map println (map #(apply str (interpose " " (reverse (re-seq #"[^s]+" %)))) (clojure.string/split poem #"n"))))

Output is the same as everyone else’s.

COBOL[edit]

       program-id. rev-word.
       data division.
       working-storage section.
       1 text-block.
        2 pic x(36) value "---------- Ice and Fire ------------".
        2 pic x(36) value "                                    ".
        2 pic x(36) value "fire, in end will world the say Some".
        2 pic x(36) value "ice. in say Some                    ".
        2 pic x(36) value "desire of tasted I've what From     ".
        2 pic x(36) value "fire. favor who those with hold I   ".
        2 pic x(36) value "                                    ".
        2 pic x(36) value "... elided paragraph last ...       ".
        2 pic x(36) value "                                    ".
        2 pic x(36) value "Frost Robert -----------------------".
       1 redefines text-block.
        2 occurs 10.
         3 text-line pic x(36).
       1 text-word.
        2 wk-len binary pic 9(4).
        2 wk-word pic x(36).
       1 word-stack.
        2 occurs 10.
         3 word-entry.
          4 word-len binary pic 9(4).
          4 word pic x(36).
       1 binary.
        2 i pic 9(4).
        2 pos pic 9(4).
        2 word-stack-ptr pic 9(4).

       procedure division.
           perform varying i from 1 by 1
           until i > 10
               perform push-words
               perform pop-words
           end-perform
           stop run
           .

       push-words.
           move 1 to pos
           move 0 to word-stack-ptr
           perform until pos > 36
               unstring text-line (i) delimited by all space
               into wk-word count in wk-len
               pointer pos
               end-unstring
               add 1 to word-stack-ptr
               move text-word to word-entry (word-stack-ptr)
           end-perform
           .

       pop-words.
           perform varying word-stack-ptr from word-stack-ptr
               by -1
           until word-stack-ptr < 1
               move word-entry (word-stack-ptr) to text-word
               display wk-word (1:wk-len) space with no advancing
           end-perform
           display space
           .
       end program rev-word.
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

CoffeeScript[edit]

Translation of: JavaScript

strReversed = '---------- Ice and Fire ------------nn
fire, in end will world the say Somen
ice. in say Somen
desire of tasted I've what Fromn
fire. favor who those with hold Inn
... elided paragraph last ...nn
Frost Robert -----------------------'

reverseString = (s) ->
  s.split('n').map((l) -> l.split(/s/).reverse().join ' ').join 'n'

console.log reverseString(strReversed)

As JavaScript.

Common Lisp[edit]

(defun split-and-reverse (str)
  (labels 
    ((iter (s lst)
       (let ((s2 (string-trim '(#space) s)))
         (if s2
             (let ((word-end (position #space s2)))
               (if (and word-end (< (1+ word-end) (length s2)))
                   (iter (subseq s2 (1+ word-end))
                         (cons (subseq s2 0 word-end) lst))
                   (cons s2 lst)))
               lst))))
  (iter str NIL)))

(defparameter *poem* 
  "---------- Ice and Fire ------------
   
   fire, in end will world the say Some
   ice. in say Some 
   desire of tasted I've what From
   fire. favor who those with hold I
 
   ... elided paragraph last ...
 
   Frost Robert -----------------------")

(with-input-from-string (s *poem*)
  (loop for line = (read-line s NIL)
        while line
        do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))

Output is the same as everyone else’s.

D[edit]

void main() {
    import std.stdio, std.string, std.range, std.algorithm;

    immutable text =
"---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------";

    writefln("%(%-(%s %)n%)",
             text.splitLines.map!(r => r.split.retro));
}

The output is the same as the Python entry.

Delphi[edit]

program RosettaCode_ReverseWordsInAString;

{$APPTYPE CONSOLE}

uses Classes, Types, StrUtils;

const
  TXT =
  '---------- Ice and Fire -----------'+sLineBreak+
  sLineBreak+
  'fire, in end will world the say Some'+sLineBreak+
  'ice. in say Some'+sLineBreak+
  'desire of tasted I''ve what From'+sLineBreak+
  'fire. favor who those with hold I'+sLineBreak+
  sLineBreak+
  '... elided paragraph last ...'+sLineBreak+
  sLineBreak+
  'Frost Robert -----------------------'+sLineBreak;

var
  i, w: Integer;
  d: TStringDynArray;
begin
  with TStringList.Create do
  try
    Text := TXT;
    for i := 0 to Count - 1 do
    begin
      d := SplitString(Strings[i], #32);
      Strings[i] := '';
      for w := Length(d) - 1 downto 0 do
        Strings[i] := Strings[i] + #32 + d[w];
    end;
    Writeln(Text);
  finally
    Free
  end;
  ReadLn;
end.

The output is the same as the Pascal entry.

EchoLisp[edit]

Using a here-string input :

(define S #<<
---------- Ice and Fire ------------
 
fire, in end will world the say Some 
ice. in say Some             
desire of tasted I've what From 
fire. favor who those with hold I 
 
... elided paragraph last ... 
 
Frost Robert -----------------------
>>#)
			
(for-each writeln 
    (for/list ((line (string-split S "n"))) 
        (string-join (reverse (string-split line " ")) " ")))
------------ Fire and Ice ----------    
    
Some say the world will end in fire,    
Some say in ice.    
From what I've tasted of desire    
I hold with those who favor fire.    
    
... last paragraph elided ...    
    
----------------------- Robert Frost    

Elena[edit]

ELENA 5.0:

import extensions;
import system'routines;
 
public program()
{
    var text := new string[]{"---------- Ice and Fire ------------",
                  "",
                  "fire, in end will world the say Some",
                  "ice. in say Some",
                  "desire of tasted I've what From",
                  "fire. favor who those with hold I",
                  "",
                  "... elided paragraph last ...",
                  "",
                  "Frost Robert -----------------------"};
 
    text.forEach:(line)
    {
        line.splitBy:" ".sequenceReverse().forEach:(word)
        {
            console.print(word," ")
        };
        console.writeLine()
    }
}

Elixir[edit]

defmodule RC do
  def reverse_words(txt) do
    txt |> String.split("n")       # split lines
        |> Enum.map(&(              # in each line
             &1 |> String.split       # split words
                |> Enum.reverse       # reverse words
                |> Enum.join(" ")))   # rejoin words
        |> Enum.join("n")          # rejoin lines
  end 
end

Usage:

txt = """
---------- Ice and Fire ------------
                                    
fire, in end will world the say Some
ice. in say Some                    
desire of tasted I've what From     
fire. favor who those with hold I   
                                    
... elided paragraph last ...       
                                    
Frost Robert -----------------------
"""

IO.puts RC.reverse_words(txt)

Elm[edit]

reversedPoem =
  String.trim """
    ---------- Ice and Fire ------------
  
    fire, in end will world the say Some
    ice. in say Some
    desire of tasted I've what From
    fire. favor who those with hold I
  
    ... elided paragraph last ...
  
    Frost Robert -----------------------
    """

reverseWords string =
  string |> String.words |> List.reverse |> String.join " "

reverseLinesWords string =
  string |> String.lines |> List.map reverseWords |> String.join "n"

poem = 
  reverseLinesWords reversedPoem

Emacs Lisp[edit]

(defun reverse-words (line)
  (insert
   (format "%sn"
           (mapconcat 'identity (reverse (split-string line)) " "))))

(defun reverse-lines (lines)
  (mapcar 'reverse-words lines))

(reverse-lines
 '("---------- Ice and Fire ------------"
   ""
   "fire, in end will world the say Some"
   "ice. in say Some"
   "desire of tasted I've what From"
   "fire. favor who those with hold I"
   ""
   "... elided paragraph last ..."
   ""
   "Frost Robert ----------------------- "))
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

F#[edit]

//Reverse words in a string. Nigel Galloway: July 14th., 2021
["  ---------- Ice and Fire ------------  ";
 "                                        ";       
 "  fire, in end will world the say Some  ";
 "  ice. in say Some                      ";
 "  desire of tasted I've what From       ";
 "  fire. favour who those with hold I    ";
 "                                        ";
 "  ... elided paragraph last ...         ";
 "                                        ";
 "  Frost Robert -----------------------  "]|>List.map(fun n->n.Split " "|>Array.filter((<>)"")|>Array.rev|>String.concat " ")|>List.iter(printfn "%s")
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favour fire.

... last paragraph elided ...

----------------------- Robert Frost

Factor[edit]

USING: io sequences splitting ;
IN: rosetta-code.reverse-words

"---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------"

"n" split [ " " split reverse " " join ] map [ print ] each
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Forth[edit]

The word «parse-name» consumes a word from input stream and places it on the stack. The word «type» takes a word from the data stack and prints it. Calling these two words before and after the recursive call effectively reverses a string.

: not-empty?  dup 0 > ;
: (reverse)  parse-name not-empty? IF recurse THEN type space ;
: reverse  (reverse) cr ;

reverse ---------- Ice and Fire ------------
reverse
reverse fire, in end will world the say Some
reverse ice. in say Some
reverse desire of tasted I've what From
reverse fire. favor who those with hold I
reverse
reverse ... elided paragraph last ...
reverse
reverse Frost Robert -----------------------

Output
Interpreted above code at the Forth console

------------ Fire and Ice ----------

Some say the world will end in fire, 
Some say in ice. 
From what I've tasted of desire 
I hold with those who favor fire. 

... last paragraph elided ... 

----------------------- Robert Frost 
 ok

Fortran[edit]

Compiled using G95 on x86 system running Puppy Linux.
Fortran syntax is mostly Fortran 77.

 character*40 words
 character*40 reversed
 logical inblank
 ierr=0
 read (5,fmt="(a)",iostat=ierr)words
 do while (ierr.eq.0)
 inblank=.true.
 ipos=1
 do i=40,1,-1
   if(words(i:i).ne.' '.and.inblank) then
     last=i
     inblank=.false.
     end if
    if(.not.inblank.and.words(i:i).eq.' ') then
      reversed(ipos:ipos+last-i)=words(i+1:last)
      ipos=ipos+last-i+1
      inblank=.true.
      end if
     if(.not.inblank.and.i.eq.1) then
       reversed(ipos:ipos+last-1)=words(1:last)
       ipos=ipos+last
       end if
   end do
 print *,words,'=> ',reversed(1:ipos-1)
 read (5,fmt="(a)",iostat=ierr)words
 end do
 end

Output from comand: cat frostPoem.txt | reverse

where file frostPoem.txt contains the input text.

 ---------- Ice and Fire -----------     => ----------- Fire and Ice ----------
                                         => 
 fire, in end will world the say Some    => Some say the world will end in fire,
 ice. in say Some                        => Some say in ice.
 desire of tasted I've what From         => From what I've tasted of desire
 fire. favor who those with hold I       => I hold with those who favor fire.
                                         => 
 ... elided paragraph last ...           => ... last paragraph elided ...
                                         => 
 Frost Robert -----------------------    => ----------------------- Robert Frost

FreeBASIC[edit]

' FB 1.05.0 Win64

Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
  If s = "" OrElse sepList = "" Then 
     Redim result(0)
     result(0) = s
     Return
  End If
  Dim As Integer i, j, count = 0, empty = 0, length
  Dim As Integer position(Len(s) + 1)
  position(0) = 0
 
  For i = 0 To len(s) - 1
    For j = 0 to Len(sepList) - 1
      If s[i] = sepList[j] Then 
        count += 1
        position(count) = i + 1       
      End If
    Next j
  Next i

  Redim result(count)
  If count  = 0 Then
    result(0) = s
    Return
  End If

  position(count + 1) = len(s) + 1
 
  For i = 1 To count + 1  
    length = position(i) - position(i - 1) - 1 
    result(i - 1 - empty) = Mid(s, position(i - 1) + 1, length)
    If removeEmpty Andalso CBool(length = 0) Then empty += 1
  Next

  If empty > 0 Then Redim Preserve result(count - empty)
End Sub

Dim s As String = "Hey you, Bub!"
Dim a() As String
split(s, " ", a(), true)
Dim reversed As String = ""
For i As Integer = UBound(a) To LBound(a) Step -1
  reversed += a(i)
  If i > LBound(a) Then reversed += " "
Next

Print "Original String = "; s
Print "Reversed String = "; reversed
Print
Print "Press any key to quit"
Sleep
Original String = Hey you, Bub!
Reversed String = Bub! you, Hey

Frink[edit]

lines=split["n", 
"""---------- Ice and Fire ------------
                                       
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
                                  
 .. elided paragraph last ...  
                                  
Frost Robert -----------------------"""]

for line = lines
    println[join[" ", reverse[split[%r/s+/, line]]]]

FutureBasic[edit]

include "NSLog.incl"

CFStringRef        frostStr
CFArrayRef         frostArr, tempArr
CFMutableStringRef mutStr
NSInteger          i, count

frostStr = @"---------- Ice and Fire ------------n¬
n¬
fire, in end will world the say Somen¬
ice. in say Somen¬
desire of tasted I've what Fromn¬
fire. favor who those with hold In¬
n¬
… elided paragraph last …n¬
n¬
Frost Robert -----------------------n"

frostArr = fn StringComponentsSeparatedByString( frostStr, @"n" )
count    = fn ArrayCount( frostArr )
mutStr   = fn MutableStringWithCapacity( 0 )

for i = 0 to count - 1
tempArr = fn StringComponentsSeparatedByString( frostArr[i], @" " )
tempArr = fn EnumeratorAllObjects( fn ArrayReverseObjectEnumerator( tempArr ) )
MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) )
MutableStringAppendString( mutStr, @"n" )
next

NSLog( @"%@", mutStr )

HandleEvents

Output:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

… last paragraph elided …

----------------------- Robert Frost

Gambas[edit]

Click this link to run this code

Public Sub Main()
Dim sString As New String[10]                                     'Array for the input text
Dim sLine As New String[]                                         'Array of each word in a line
Dim siCount0, siCount1 As Short                                   'Counters
Dim sOutput, sReverse, sTemp As String                            'Strings

sString[0] = "---------- Ice And Fire ------------"               'Input text
sString[1] = "                                    "
sString[2] = "fire, in end will world the say Some"
sString[3] = "ice. in say Some                    "
sString[4] = "desire of tasted I've what From     "
sString[5] = "fire. favor who those with hold I   " 
sString[6] = "                                    "
sString[7] = "... elided paragraph last ...       "
sString[8] = "                                    "
sString[9] = "Frost Robert -----------------------"

For siCount0 = 0 To 9                                             'To work through each line of input text
  If Trim(sString[siCount0]) = "" Then sString[siCount0] = " "    'If the line is all spaces then make it 1 space
  
  For Each sTemp In Split(Trim(sString[siCount0]), " ")           'Split the trimmed line by spaces
    sLine.Add(sTemp)                                              'Add each word to the sLine array
  Next
  
  For siCount1 = sLine.max DownTo 0                               'Loop from the last in the sLine array to 0
    sReverse &= sLine[siCount1] & " "                             'Fill sReverse with words reversed, adding a space
  Next
  
  sOutput &= Trim(sReverse) & gb.NewLine                          'Add the reversed words to sOutput and add a newline
  sReverse = ""                                                   'Clear sReverse
  sLine.Clear                                                     'Clear sLine array
Next

Print sOutput                                                     'Print the output

End

Output:

------------ Fire And Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Gema[edit]

Go[edit]

package main

import (
    "fmt"
    "strings"
)

// a number of strings
var n = []string{
    "---------- Ice and Fire ------------",
    "                                    ",
    "fire, in end will world the say Some",
    "ice. in say Some                    ",
    "desire of tasted I've what From     ",
    "fire. favor who those with hold I   ",
    "                                    ",
    "... elided paragraph last ...       ",
    "                                    ",
    "Frost Robert -----------------------",
}

func main() {
    for i, s := range n {
        t := strings.Fields(s) // tokenize
        // reverse
        last := len(t) - 1
        for j, k := range t[:len(t)/2] {
            t[j], t[last-j] = t[last-j], k
        }
        n[i] = strings.Join(t, " ")
    }
    // display result
    for _, t := range n {
        fmt.Println(t)
    }
}
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Groovy[edit]

def text = new StringBuilder()
    .append('---------- Ice and Fire ------------n')
    .append('                                    n')
    .append('fire, in end will world the say Somen')
    .append('ice. in say Some                    n')
    .append('desire of tasted I've what From     n')
    .append('fire. favor who those with hold I   n')
    .append('                                    n')
    .append('... elided paragraph last ...       n')
    .append('                                    n')
    .append('Frost Robert -----------------------n').toString()

text.eachLine { line ->
    println "$line   -->   ${line.split(' ').reverse().join(' ')}"
}
---------- Ice and Fire ------------   -->   ------------ Fire and Ice ----------
                                       -->   
fire, in end will world the say Some   -->   Some say the world will end in fire,
ice. in say Some                       -->   Some say in ice.
desire of tasted I've what From        -->   From what I've tasted of desire
fire. favor who those with hold I      -->   I hold with those who favor fire.
                                       -->   
... elided paragraph last ...          -->   ... last paragraph elided ...
                                       -->   
Frost Robert -----------------------   -->   ----------------------- Robert Frost

Haskell[edit]

revstr :: String -> String
revstr = unwords . reverse . words -- point-free style
--equivalent:
--revstr s = unwords (reverse (words s))

revtext :: String -> String
revtext = unlines . map revstr . lines -- applies revstr to each line independently

test = revtext "---------- Ice and Fire ------------n
        \n
        fire, in end will world the say Somen
        ice. in say Somen
        desire of tasted I've what Fromn
        fire. favor who those with hold In
        \n
        ... elided paragraph last ...n
        \n
        Frost Robert -----------------------n" --multiline string notation requires  at end and start of lines, and n to be manually input

unwords, reverse, words, unlines, map and lines are built-in functions, all available at GHC’s Prelude.
For better visualization, use «putStr test»

Icon and Unicon[edit]

Works in both languages:

procedure main()
    every write(rWords(&input))
end

procedure rWords(f)
    every !f ? {
        every (s := "") := genWords() || s
        suspend s
        }
end

procedure genWords()
    while w := 1(tab(upto(" t")),tab(many(" t"))) || " " do suspend w
end

for test file

->rw <rw.in
------------ Fire and Ice ----------  
 
Some say the world will end in fire,  
Some say in ice.  
From what I've tasted of desire  
I hold with those who favor fire.  
 
... last paragraph elided ...  
 
----------------------- Robert Frost  
->

J[edit]

Treated interactively:

   ([:;@|.[:<;.1 ' ',]);._2]0 :0
---------- Ice and Fire ------------

  fire, in end will world the say Some
  ice. in say Some
  desire of tasted I've what From
  fire. favor who those with hold I

   ... elided paragraph last ...

  Frost Robert -----------------------
)
 ------------ Fire and Ice ----------  
                                       
 Some say the world will end in fire,  
 Some say in ice.                      
 From what I've tasted of desire       
 I hold with those who favor fire.     
                                       
 ... last paragraph elided ...         
                                       
 ----------------------- Robert Frost

The verb phrase ( [:  ; @ |. [: < ;. 1 ' ' , ]) reverses words in a string. The rest of the implementation has to do with defining the block of text we are working on, and applying this verb phrase to each line of that text.

Another approach:

echo ;:inv@|.@cut;._2 {{)n
---------- Ice and Fire ------------
 
  fire, in end will world the say Some
  ice. in say Some
  desire of tasted I've what From
  fire. favor who those with hold I
 
   ... elided paragraph last ...
 
  Frost Robert -----------------------
}}

produces:

------------ Fire and Ice ----------
                                    
Some say the world will end in fire,
Some say in ice.                    
From what I've tasted of desire     
I hold with those who favor fire.   
                                    
... last paragraph elided ...       
                                    
----------------------- Robert Frost

Java[edit]

public class ReverseWords {

    static final String[] lines = {
        " ----------- Ice and Fire ----------- ",
        "                                      ",
        " fire, in end will world the say Some ",
        " ice. in say Some                     ",
        " desire of tasted I've what From      ",
        " fire. favor who those with hold I    ",
        "                                      ",
        " ... elided paragraph last ...        ",
        " Frost Robert ----------------------- "};

    public static void main(String[] args) {
        for (String line : lines) {
            String[] words = line.split("\s");
            for (int i = words.length - 1; i >= 0; i--)
                System.out.printf("%s ", words[i]);
            System.out.println();
        }
    }
}

Works with: Java version 8+

package string;

import static java.util.Arrays.stream;

public interface ReverseWords {
  public static final String[] LINES = {
    " ----------- Ice and Fire ----------- ",
    "                                      ",
    " fire, in end will world the say Some ",
    " ice. in say Some                     ",
    " desire of tasted I've what From      ",
    " fire. favor who those with hold I    ",
    "                                      ",
    " ... elided paragraph last ...        ",
    " Frost Robert ----------------------- "
  };

  public static String[] reverseWords(String[] lines) {
    return stream(lines)
      .parallel()
      .map(l -> l.split("\s"))
      .map(ws -> stream(ws)
        .parallel()
        .map(w -> " " + w)
        .reduce(
          "",
          (w1, w2) -> w2 + w1
        )
      )
      .toArray(String[]::new)
    ;
  }
 
  public static void main(String... arguments) {
    stream(reverseWords(LINES))
      .forEach(System.out::println)
    ;
  }
}
----------- Fire and Ice ----------- 

Some say the world will end in fire,   
Some say in ice.   
From what I've tasted of desire   
I hold with those who favor fire.   

... last paragraph elided ...   

----------------------- Robert Frost 

JavaScript[edit]

var strReversed =
"---------- Ice and Fire ------------n
n
fire, in end will world the say Somen
ice. in say Somen
desire of tasted I've what Fromn
fire. favor who those with hold In
n
... elided paragraph last ...n
n
Frost Robert -----------------------";
    
function reverseString(s) {
  return s.split('n').map(
    function (line) {
      return line.split(/s/).reverse().join(' ');
    }
  ).join('n');
}
  
console.log(
  reverseString(strReversed)
);

Output:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

jq[edit]

split("[ tnr]+") | reverse | join(" ")

This solution requires a version of jq with regex support for split.

The following example assumes the above line is in a file named reverse_words.jq and that the input text is in a file named IceAndFire.txt. The -r option instructs jq to read the input file as strings, line by line.

$ jq -R -r -M -f reverse_words.jq IceAndFire.txt
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Jsish[edit]

From Javascript entry.

var strReversed =
"---------- Ice and Fire ------------n
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
n... elided paragraph last ...n
Frost Robert -----------------------";
 
function reverseString(s) {
    return s.split('n').map(
      function (line) {
          return line.split().reverse().join(' ');
      }
    ).join('n');
}

;reverseString('Hey you, Bub!');
;strReversed;
;reverseString(strReversed);

/*
=!EXPECTSTART!=
reverseString('Hey you, Bub!') ==> Bub! you, Hey
strReversed ==> ---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------
reverseString(strReversed) ==> ------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost
=!EXPECTEND!=
*/
prompt$ jsish -u reverseWords.jsi
[PASS] reverseWords.jsi

Julia[edit]

revstring (str) = join(reverse(split(str, " ")), " ")
julia> revstring("Hey you, Bub!")
"Bub! you, Hey"

julia> s = IOBuffer(
"---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------")

julia>  for line in eachline(s)
          println(revstring(chomp(line)))
        end
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost

Kotlin[edit]

fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")

fun main() {
    val s = "Hey you, Bub!"
    println(reversedWords(s))
    println()
    val sl = listOf(
        " ---------- Ice and Fire ------------ ", 
        "                                      ",
        " fire, in end will world the say Some ", 
        " ice. in say Some                     ", 
        " desire of tasted I've what From      ", 
        " fire. favor who those with hold I    ",  
        "                                      ",  
        " ... elided paragraph last ...        ", 
        "                                      ",  
        " Frost Robert ----------------------- ",
    ) 
    sl.forEach { println(reversedWords(it)) }
}
Bub! you, Hey

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Ksh[edit]

#!/bin/ksh

# Reverse words in a string

#	# Variables:
#
typeset -a wArr
integer i


 ######
# main #
 ######

while read -A wArr; do
	for ((i=${#wArr[@]}-1; i>=0; i--)); do
		printf "%s " "${wArr[i]}"
	done
	echo
done << EOF
---------- Ice and Fire ------------
                                    
fire, in end will world the say Some
ice. in say Some                    
desire of tasted I've what From     
fire. favor who those with hold I   
                                    
... elided paragraph last ...       
Frost Robert -----------------------
EOF

------------ Fire and Ice ----------

Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Lambdatalk[edit]

This answer illustrates how a missing primitive (line_split) can be added directly in the wiki page.

1) We write a function

{def line_reverse
 {def line_reverse.r
  {lambda {:i :txt :length}
   {if {> :i :length}
    then 
    else {br}{A2S {A.reverse! {A.get :i :txt}}}
         {line_reverse.r {+ :i 1} :txt :length}}}}
 {lambda {:txt}
  {let { {:a {line_split {:txt}}} }
  {line_reverse.r 0 :a {- {A.length :a} 1}}}} }
-> line_reverse

where A2S translates an array into a sentence

{def A2S           
 {lambda {:a}
  {if {A.empty? :a}
   then 
   else {A.first :a} {A2S {A.rest :a}}}}}
-> A2S

and line_split is a javascript primitive directly written in the wiki page, 
added to the dictionary and returning an array of lines

LAMBDATALK.DICT['line_split'] = function () {
  var args = arguments[0].split("n");
  var str = "{A.new ";
  for (var i=0; i< args.length; i++)
    str += "{A.new " + args[i] + "} ";
  str += "}";
  return LAMBDATALK.eval_forms( str ) 
};

2) input (from a simple text source without any presetting)

{def rosetta
---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I''ve what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------
}
-> rosetta

3) calling the function:

{line_reverse rosetta}
->

3) output

------------ Fire and Ice ----------  

Some say the world will end in fire,  
Some say in ice.  
From what I''ve tasted of desire  
I hold with those who favor fire.  

... last paragraph elided ...
  
----------------------- Robert Frost

Liberty BASIC[edit]

for i = 1 to 10
    read string$
    print reverse$(string$)
next
end

function reverse$(string$)
    token$="*"
    while token$<>""
        i=i+1
        token$ = word$(string$, i)
        output$=token$+" "+output$
    wend
    reverse$ = trim$(output$)
end function

data "---------- Ice and Fire ------------"
data ""
data "fire, in end will world the say Some"
data "ice. in say Some"
data "desire of tasted I've what From"
data "fire. favor who those with hold I"
data ""
data "... elided paragraph last ..."
data ""
data "Frost Robert -----------------------"
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

LiveCode[edit]

The input text has been entered into the contents of a text field called «Fieldtxt», add a button and put the following in its mouseUp

repeat for each line txtln in fld "Fieldtxt"
    repeat with i = the number of words of txtln down to 1
        put word i of txtln & space after txtrev
    end repeat
    put cr after txtrev  -- preserve line
end repeat
put txtrev

LiveScript[edit]

poem =
    """
    ---------- Ice and Fire ------------

    fire, in end will world the say Some
    ice. in say Some 
    desire of tasted I've what From
    fire. favor who those with hold I

    ... elided paragraph last ...

    Frost Robert -----------------------
    """

reverse-words  = (.split ' ') >> (.reverse!) >> (.join ' ')
reverse-string = (.split 'n') >> (.map reverse-words) >> (.join 'n')
reverse-string poem

Logo[edit]

This version just reads the words from standard input.

do.until [
  make "line readlist
  print reverse :line
] [word? :line]
bye

Given this input:

---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------

it produces this output:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Lua[edit]

See below for original entry and the input string under variable ‘s’. Here is a significantly shorter program.

local lines = {}
for line in (s .. "n"):gmatch("(.-)n") do
	local this = {}
	for word in line:gmatch("%S+") do
		table.insert(this, 1, word)
	end
	lines[#lines + 1] = table.concat(this, " ")
end
print(table.concat(lines, "n"))

Original response:

(Note: The Wiki’s syntax highlighting for Lua does not highlight the following valid string literal correctly, so the listing is split in two parts.)

   s = [[---------- Ice and Fire ------------
   
   fire, in end will world the say Some
   ice. in say Some
   desire of tasted I've what From
   fire. favor who those with hold I
   
   ... elided paragraph last ...
   
   Frost Robert -----------------------
   ]]
function table.reverse(a)
    local res = {}
    for i = #a, 1, -1 do
        res[#res+1] = a[i]
    end
    return res
end

function splittokens(s)
    local res = {}
    for w in s:gmatch("%S+") do
        res[#res+1] = w
    end
    return res
end

for line, nl in s:gmatch("([^n]-)(n)") do
    print(table.concat(table.reverse(splittokens(line)), ' '))
end

Note: With the technique used here for splitting s into lines (not part of the task) the last line will be gobbled up if it does not end with a newline.

Maple[edit]

while (true) do
	input := readline("input.txt"):
	if input = 0 then break: fi:
	input := StringTools:-Trim(input): # remove leading/trailing space
	input := StringTools:-Join(ListTools:-Reverse(StringTools:-Split(input, " "))," "):
	printf("%sn", input):
od:
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Mathematica/Wolfram Language[edit]

poem = "---------- Ice and Fire ------------
   
     fire, in end will world the say Some
     ice. in say Some 
     desire of tasted I've what From
     fire. favor who those with hold I
   
     ... elided paragraph last ...
   
     Frost Robert -----------------------";
lines = StringSplit[poem, "n"];
wordArray = StringSplit[#] &   @ lines ;
reversedWordArray = Reverse[#] & /@ wordArray ;
linesWithReversedWords = 
  StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "n"]] &  @ linesWithReversedWords
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

MATLAB / Octave[edit]

function testReverseWords
    testStr = {'---------- Ice and Fire ------------' ; ...
        ''                                            ; ...
        'fire, in end will world the say Some'        ; ...
        'ice. in say Some'                            ; ...
        'desire of tasted I''ve what From'            ; ...
        'fire. favor who those with hold I'           ; ...
        ''                                            ; ...
        '... elided paragraph last ...'               ; ...
        ''                                            ; ...
        'Frost Robert -----------------------'        };
    for k = 1:length(testStr)
        fprintf('%sn', reverseWords(testStr{k}))
    end
end

function strOut = reverseWords(strIn)
    strOut = strtrim(strIn);
    if ~isempty(strOut)
        % Could use strsplit() instead of textscan() in R2013a or later
        words = textscan(strOut, '%s');
        words = words{1};
        strOut = strtrim(sprintf('%s ', words{end:-1:1}));
    end
end
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

MAXScript[edit]

-- MAXScript : Reverse words in a string : N.H. 2019
--
(
text = stringstream "---------- Ice and Fire ------------nnfire, in end will world the say Somenice. in say Somendesire of tasted I've what Fromnfire. favor who those with hold Inn... elided paragraph last ...nnFrost Robert -----------------------n"
clearListener()
seek text 0
while eof text == false do
(
nextLine = (readLine text)
if nextLine == "" then
(
print ""
continue	
) -- end of if
revLine = ""
eachWord = filterString nextLine " "
for k = eachWord.count to 1 by -1 do
(
revLine = revLine + eachWord[k]
-- Only add space between words not at the end of line
if k != 1 then revLine = revLine + " "
) -- end of for k
print revLine
) -- end of while eof
)

Output to MAXScript Listener:

"------------ Fire and Ice ----------"
""
"Some say the world will end in fire,"
"Some say in ice."
"From what I've tasted of desire"
"I hold with those who favor fire."
""
"... last paragraph elided ..."
""
"----------------------- Robert Frost"

MiniScript[edit]

lines = ["==========================================",
    "|  ---------- Ice and Fire ------------  |",
    "|                                        |",
    "|  fire, in end will world the say Some  |",
    "|  ice. in say Some                      |",
    "|  desire of tasted I've what From       |",
    "|  fire. favor who those with hold I     |",
    "|                                        |",
    "|  ... elided paragraph last ...         |",
    "|                                        |",
    "|  Frost Robert -----------------------  |",
    "=========================================="]
    
for line in lines
    oldLine = line.split
    newLine = []
    while oldLine
// the line below line retains the outer box format
        newLine.push oldLine.pop
// alternate format, replace above line with below two lines below to strip all superfluous spaces
//	word = oldLine.pop
//	if word != "" then newLine.push word
    end while
    print newLine.join
end for
==========================================
|  ------------ Fire and Ice ----------  |
|                                        |
|  Some say the world will end in fire,  |
|                      Some say in ice.  |
|       From what I've tasted of desire  |
|     I hold with those who favor fire.  |
|                                        |
|         ... last paragraph elided ...  |
|                                        |
|  ----------------------- Robert Frost  |
==========================================

Modula-2[edit]

Translation of: Pascal

Works with: ADW Modula-2 version any (Compile with the linker option Console Application).

MODULE ReverseWords;

FROM STextIO IMPORT
  WriteString, WriteLn;
FROM Strings IMPORT
  Assign, Concat, Append;

CONST
  NL = CHR(10);
  Sp = ' ';
  Txt = "---------- Ice and Fire -----------" + NL +
    NL +
    "fire, in end will world the say Some" + NL +
    "ice. in say Some" + NL +
    "desire of tasted I've what From" + NL +
    "fire. favor who those with hold I" + NL +
    NL +
    "... elided paragraph last ..." + NL +
    NL +
    "Frost Robert -----------------------" + NL;

TYPE
  String400 = ARRAY [0 .. 399] OF CHAR;

PROCEDURE AddWord(Source: ARRAY OF CHAR; VAR INOUT Destination: ARRAY OF CHAR);
VAR
  R: String400;
BEGIN
  Concat(Source, Sp, R);
  Append(Destination, R);
  Assign(R, Destination);
END AddWord;

VAR
  I: CARDINAL;
  SingleWord, CurrentLine: String400;
  C: CHAR;

BEGIN
  SingleWord := "";
  CurrentLine := "";
  FOR I := 0 TO HIGH(Txt) DO
    C := Txt[I];
    CASE C OF
      Sp:
        AddWord(SingleWord, CurrentLine);
        SingleWord := ""; |
      NL:
        AddWord(SingleWord, CurrentLine);
        WriteString(CurrentLine);
        WriteLn;
        SingleWord := "";
        CurrentLine := ""; |
    ELSE
      Append(C, SingleWord);
    END;
  END;
END ReverseWords.

Nanoquery[edit]

def reverse_words(string)
        tokens = split(string, " ")
        if len(tokens) = 0
                return ""
        end

        ret_str = ""
        for i in range(len(tokens) - 1, 0)
                ret_str += tokens[i] + " "
        end
        return ret_str.substring(0, len(ret_str) - 1)
end

data = "---------- Ice and Fire ------------n" +
       "                                    n" +
       "fire, in end will world the say Somen" +
       "ice. in say Some                    n" +
       "desire of tasted I've what From     n" +
       "fire. favor who those with hold I   n" +
       "                                    n" +
       "... elided paragraph last ...       n" +
       "Frost Robert -----------------------n"

for line in split(data, "n")
        println reverse_words(line)
end
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...
----------------------- Robert Frost

Nial[edit]

# Define a function to convert a list of strings to a single string.
join is rest link (' ' eachboth link)

iterate (write join reverse (' ' string_split)) 
  
  
  '------------ Eldorado ----------' 
  '' 
  '... here omitted lines ...' 
  '' 
  'Mountains the "Over' 
  'Moon, the Of' 
  'Shadow, the of Valley the Down' 
  'ride," boldly Ride,' 
  'replied,--- shade The' 
  'Eldorado!" for seek you "If' 
  '' 
  'Poe Edgar -----------------------'
---------- Eldorado ------------

... lines omitted here ...

"Over the Mountains
Of the Moon,
Down the Valley of the Shadow,
Ride, boldly ride,"
The shade replied,---
"If you seek for Eldorado!"

----------------------- Edgar Poe

Nim[edit]

import strutils

let text = """---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------"""

proc reversed*[T](a: openArray[T], first, last: int): seq[T] =
  result = newSeq[T](last - first + 1)
  var x = first
  var y = last
  while x <= last:
    result[x] = a[y]
    dec(y)
    inc(x)

proc reversed*[T](a: openArray[T]): seq[T] =
  reversed(a, 0, a.high)

for line in text.splitLines():
  echo line.split(' ').reversed().join(" ")
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Objeck[edit]

use Collection;

class Reverselines {
  function : Main(args : String[]) ~ Nil {
    lines := List->New();
    lines->AddBack("---------- Ice and Fire ------------");
    lines->AddBack("");
    lines->AddBack("fire, in end will world the say Some");
    lines->AddBack("ice. in say Some");
    lines->AddBack("desire of tasted I've what From");
    lines->AddBack("fire. favor who those with hold I");
    lines->AddBack("");
    lines->AddBack("... elided paragraph last ...");
    lines->AddBack("");
    lines->AddBack("Frost Robert -----------------------");
    
    lines->Rewind();
    each(i : lines) {
      words := lines->Get()->As(String)->Split(" ");
      if(words <> Nil) {      
        for(j := words->Size() - 1; j > -1; j-=1;) {
          IO.Console->Print(words[j])->Print(" ");
        };
      };
      IO.Console->PrintLine();
      lines->Next();
    };
  }
}
------------ Fire and Ice ---------- 

Some say the world will end in fire, 
Some say in ice. 
From what I've tasted of desire 
I hold with those who favor fire. 

... last paragraph elided ... 

----------------------- Robert Frost 

OCaml[edit]

#load "str.cma"
let input = ["---------- Ice and Fire ------------";
        "";
        "fire, in end will world the say Some";
        "ice. in say Some";
        "desire of tasted I've what From";
        "fire. favor who those with hold I";
        "";
        "... elided paragraph last ...";
        "";
        "Frost Robert -----------------------"];;

let splitted = List.map (Str.split (Str.regexp " ")) input in
let reversed = List.map List.rev splitted in
let final = List.map (String.concat " ") reversed in
List.iter print_endline final;;

Sample usage

$ ocaml reverse.ml
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Oforth[edit]

: revWords(s) 
   s words reverse unwords ;

: reverseWords
   "---------- Ice and Fire ------------" revWords println
   "                                    " revWords println
   "fire, in end will world the say Some" revWords println
   "ice. in say Some                    " revWords println
   "desire of tasted I've what From     " revWords println
   "fire. favor who those with hold I   " revWords println
   "                                    " revWords println
   "... elided paragraph last ...       " revWords println
   "                                    " revWords println
   "Frost Robert -----------------------" revWords println ;
>reverseWords
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost
ok

Pascal[edit]

Free Pascal 3.0.0

program Reverse_words(Output);
{$H+}

const
  nl = chr(10); // Linefeed
  sp = chr(32); // Space
  TXT =
  '---------- Ice and Fire -----------'+nl+
  nl+
  'fire, in end will world the say Some'+nl+
  'ice. in say Some'+nl+
  'desire of tasted I''ve what From'+nl+
  'fire. favor who those with hold I'+nl+
  nl+
  '... elided paragraph last ...'+nl+
  nl+
  'Frost Robert -----------------------'+nl;

var
  I : integer;
  ew, lw : ansistring;
  c : char;

function addW : ansistring;
var r : ansistring = '';
begin
  r := ew + sp + lw;
  ew := '';
  addW := r
end;

begin
  ew := '';
  lw := '';

  for I := 1 to strlen(TXT) do
  begin
    c := TXT[I];
    case c of
      sp : lw := addW;
      nl : begin writeln(addW); lw := '' end;
      else ew := ew + c
    end;
  end;
  readln;
end.
----------- Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Another version (tested with FPC 3.2.2)

program reverse_words;
{$mode objfpc}{$h+}
uses
  SysUtils;

function Reverse(a: TStringArray): TStringArray;
var
  I, J: SizeInt;
  t: Pointer;
begin
  I := 0;
  J := High(a);
  while I < J do begin
    t := Pointer(a[I]);
    Pointer(a[I]) := Pointer(a[J]);
    Pointer(a[J]) := t;
    Inc(I);
    Dec(J);
  end;
  Result := a;
end;

const
  Input =
    '---------- Ice and Fire -----------'  + LineEnding +
                                        '' + LineEnding +
    'fire, in end will world the say Some' + LineEnding +
    'ice. in say Some'                     + LineEnding +
    'desire of tasted I''ve what From'     + LineEnding +
    'fire. favor who those with hold I'    + LineEnding +
                                        '' + LineEnding +
    '... elided paragraph last ...'        + LineEnding +
                                        '' + LineEnding +
    'Frost Robert -----------------------' + LineEnding;
var
  Line: string;

begin
  for Line in Input.Split([LineEnding], TStringSplitOptions.ExcludeLastEmpty) do
    WriteLn(string.Join(' ', Reverse(Line.Split([' ']))));
end.

Perl[edit]

print join(" ", reverse split), "n" for <DATA>;
__DATA__
---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some                    
desire of tasted I've what From     
fire. favor who those with hold I   
 
... elided paragraph last ...       
 
Frost Robert -----------------------

Phix[edit]

with javascript_semantics
constant test="""
---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------
"""
sequence lines = split(test,'n')
for i=1 to length(lines) do
    lines[i] = join(reverse(split(lines[i])))
end for
puts(1,join(lines,"n"))
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Phixmonti[edit]

include ..Utilitys.pmt

"---------- Ice and Fire ------------"
"" 
"fire, in end will world the say Some"
"ice. in say Some"
"desire of tasted I've what From"
"fire. favor who those with hold I"
"" 
"... elided paragraph last ..."
"" 
"Frost Robert -----------------------"

stklen tolist
len for var i
    i get split reverse i set 
endfor
len for
    get len dup if
        for get print " " print endfor
    else drop endif
    drop nl
endfor
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

PHP[edit]

 
<?php
 
 function strInv ($string) {

 	$str_inv = '' ; 

	 for ($i=0,$s=count($string);$i<$s;$i++){
	 	$str_inv .= implode(' ',array_reverse(explode(' ',$string[$i])));
	 	$str_inv .= '<br>';
	 }

 	return $str_inv;

 }
  
 $string[] =  "---------- Ice and Fire ------------";
 $string[] =  "";
 $string[] =  "fire, in end will world the say Some";
 $string[] =  "ice. in say Some";
 $string[] =  "desire of tasted I've what From";
 $string[] =  "fire. favor who those with hold I";
 $string[] =  "";
 $string[] =  "... elided paragraph last ...";
 $string[] =  "";
 $string[] =  "Frost Robert ----------------------- ";


echo strInv($string);

Output:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

PicoLisp[edit]

(in "FireIce.txt" 
 (until (eof)
  (prinl (glue " " (flip (split (line) " "))))))

Same as anybody else.

Pike[edit]

string story = #"---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------";

foreach(story/"n", string line)
    write("%sn", reverse(line/" ")*" ");

PL/I[edit]

rev: procedure options (main);          /* 5 May 2014 */
   declare (s, reverse) character (50) varying;
   declare (i, j) fixed binary;
   declare in file;

   open file (in) title ('/REV-WRD.DAT,type(text),recsize(5> Nil) {      
        for(j := words->Size() - 1; j > -1; j-=1;) {
          IO.Console->Print(words[j])->Print(" ");
        };
      };
      IO.Console->PrintLine();
      lines->Next();
    };
  }
}0)');

   do j = 1 to 10;
      get file (in) edit (s) (L);
      put skip list (trim(s));

      reverse = '';

      do while (length(s) > 0);
         s = trim(s);
         i = index(s, ' ');
         if i = 0 then
            if s ^= '' then i = length(s)+1;
         if i > 0 then reverse = substr(s, 1, i-1) || ' ' || reverse;
         if length(s) = i then s = ''; else s = substr(s, i);
      end;
      put edit ('---> ', reverse) (col(40), 2 A);
   end;
end rev;
---------- Ice and Fire ------------   ---> ------------ Fire and Ice ---------- 
                                       ---> 
fire, in end will world the say Some   ---> Some say the world will end in fire, 
ice. in say Some                       ---> Some say in ice. 
desire of tasted I've what From        ---> From what I've tasted of desire 
fire. favor who those with hold I      ---> I hold with those who favor fire. 
                                       ---> 
... elided paragraph last ...          ---> ... last paragraph elided ... 
                                       ---> 
Frost Robert -----------------------   ---> ----------------------- Robert Frost 

PowerShell[edit]

Function Reverse-Words($lines) {
    $lines | foreach { 
        $array = $PSItem.Split(' ') 
        $array[($array.Count-1)..0] -join ' '
    } 
}

$lines =
"---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
"",
"Frost Robert -----------------------"

Reverse-Words($lines)

output :

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

PureBasic[edit]

a$ =    "---------- Ice and Fire ------------" +#CRLF$+
        "                                    " +#CRLF$+
        "fire, in end will world the say Some" +#CRLF$+
        "ice. in say Some                    " +#CRLF$+
        "desire of tasted I've what From     " +#CRLF$+
        "fire. favor who those with hold I   " +#CRLF$+
        "                                    " +#CRLF$+
        "... elided paragraph last ...       " +#CRLF$+
        "                                    " +#CRLF$+
        "Frost Robert -----------------------" +#CRLF$
a$ =    "Hey you, Bub!                       " +#CRLF$+#CRLF$+ a$

OpenConsole()
For p1=1 To CountString(a$,#CRLF$)
  b$=StringField(a$,p1,#CRLF$) : c$=""  
  For p2=1 To CountString(b$,Chr(32))+1  
    c$=StringField(b$,p2,Chr(32))+Space(1)+c$    
  Next  
  PrintN(LSet(b$,36,Chr(32))+" ---> "+Trim(c$))  
Next
Input()
Hey you, Bub!                        ---> Bub! you, Hey
                                     --->
---------- Ice and Fire ------------ ---> ------------ Fire and Ice ----------
                                     --->
fire, in end will world the say Some ---> Some say the world will end in fire,
ice. in say Some                     ---> Some say in ice.
desire of tasted I've what From      ---> From what I've tasted of desire
fire. favor who those with hold I    ---> I hold with those who favor fire.
                                     --->
... elided paragraph last ...        ---> ... last paragraph elided ...
                                     --->
Frost Robert ----------------------- ---> ----------------------- Robert Frost

Python[edit]

 text = '''
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------'''

for line in text.split('n'): print(' '.join(line.split()[::-1]))

Output:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Quackery[edit]

  ' [ $ "  ---------- Ice and Fire ------------  "
      $ ""
      $ "   fire, in end will world the say Some "
      $ "   ice. in say Some                     "
      $ "   desire of tasted I've what From      "
      $ "   fire. favor who those with hold I    "
      $ ""
      $ "   ... elided paragraph last ...        "
      $ ""
      $ "   Frost Robert ----------------------- " ]
 
  witheach
    [ do nest$ reverse 
         witheach
           [ echo$ sp ]
      cr ]
------------ Fire and Ice ---------- 

Some say the world will end in fire, 
Some say in ice. 
From what I've tasted of desire 
I hold with those who favor fire. 

... last paragraph elided ... 

----------------------- Robert Frost 

R[edit]

whack <- function(s) {
  paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }

poem <- unlist( strsplit(
'------------ Eldorado ----------

... here omitted lines ...

Mountains the "Over
Moon, the Of
Shadow, the of Valley the Down
ride," boldly Ride,
replied,--- shade The
Eldorado!" for seek you "If

Poe Edgar -----------------------', "n"))

for (line in poem) cat( whack(line), "n" )
---------- Eldorado ------------

... lines omitted here ...

"Over the Mountains
Of the Moon,
Down the Valley of the Shadow,
Ride, boldly ride,"
The shade replied,---
"If you seek for Eldorado!"

----------------------- Edgar Poe

As a dangerous stunt, let’s redefine «{«.
(Everything that happens in R is a function-call.)

> `{`  <-  function(s) rev(unlist(strsplit(s, " ")))
> {"one two three four five"}
[1] "five"  "four"  "three" "two"   "one"

You had better restart your REPL after trying this.

Racket[edit]

#lang racket/base

(require racket/string)

(define (split-reverse str)
  (string-join 
   (reverse 
    (string-split str))))

(define poem 
  "---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------")


(let ([poem-port (open-input-string poem)])
  (let loop ([l (read-line poem-port)])
    (unless (eof-object? l)
      (begin (displayln (split-reverse l))
              (loop (read-line poem-port))))))

In Wheeler-readable/sweet notation (https://readable.sourceforge.io/) as implemented by Asumu Takikawa (https://github.com/takikawa/sweet-racket):

#lang sweet-exp racket/base
require racket/string

define split-reverse(str)
  string-join $ reverse $ string-split str

define poem 
  "---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------"
 
let
  \
    poem-port $ open-input-string poem
  let loop
    \
      l $ read-line poem-port
    unless eof-object?(l)
      begin
        displayln split-reverse(l)
        loop read-line(poem-port)

Raku[edit]

(formerly Perl 6)
We’ll read input from stdin

say ~.words.reverse for lines
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Red[edit]

Red []
foreach line
split 
{---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------} newline [
 print reverse split line " "
]

REXX[edit]

natural order[edit]

This REXX version process the words in a natural order (first to last).

/*REXX program reverses the order of tokens in a string (but not the letters).*/
@.=;                    @.1  =  "---------- Ice and Fire ------------"
                        @.2  =  ' '
                        @.3  =  "fire, in end will world the say Some"
                        @.4  =  "ice. in say Some"
                        @.5  =  "desire of tasted I've what From"
                        @.6  =  "fire. favor who those with hold I"
                        @.7  =  ' '
                        @.8  =  "... elided paragraph last ..."
                        @.9  =  ' '
                        @.10 =  "Frost Robert -----------------------"

  do j=1  while  @.j==''              /*process each of the 10 lines of poem.*/
  $=                                   /*nullify the  $  string (the new line)*/
     do k=1  for  words(@.j)           /*process each word in a   @.j  string.*/
     $=word(@.j,k) $                   /*prepend a word to the new line  ($). */
     end   /*k*/                       /* [↑]  we could do this another way.  */

  say $                                /*display the newly constructed line.  */
  end      /*j*/                       /*stick a fork in it,  we're all done. */

output   when using the (internal text) ten lines of input:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

reverse order[edit]

This REXX version process the words in reverse order (last to first).

/*REXX program reverses the order of tokens in a string (but not the letters).*/
@.=;                    @.1  =  "---------- Ice and Fire ------------"
                        @.2  =  ' '
                        @.3  =  "fire, in end will world the say Some"
                        @.4  =  "ice. in say Some"
                        @.5  =  "desire of tasted I've what From"
                        @.6  =  "fire. favor who those with hold I"
                        @.7  =  ' '
                        @.8  =  "... elided paragraph last ..."
                        @.9  =  ' '
                        @.10 =  "Frost Robert -----------------------"

  do j=1  while  @.j==''              /*process each of the 10 lines of poem.*/
  $=                                   /*nullify the  $  string (the new line)*/
     do k=words(@.j)   to 1   by -1    /*process each word in a   @.j  string.*/
     $=$  word(@.j,k)                  /*append a word to the new line  ($).  */
     end   /*k*/                       /* [↑]  process last word to first word*/

  say $                                /*display the newly constructed line.  */
  end      /*j*/                       /*stick a fork in it,  we're all done. */

output   is the same as the 1st REXX version.

Ring[edit]

aList = str2list("
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------
")
aList = str2list(cStr)
for x in aList
   x2 = substr(x," ",nl) alist2 = str2list(x2) aList2 = reverse(aList2)
   for y in aList2 see y + " " next see nl
next

Output

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...
----------------------- Robert Frost

Ruby[edit]

puts <<EOS
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------
EOS
  .each_line.map {|line| line.split.reverse.join(' ')}

Output the same as everyone else’s.

Run BASIC[edit]

for i = 1 to 10
    read string$
   j = 1
   r$ = ""
    while word$(string$,j) <> ""
     r$ = word$(string$,j) + " " + r$
     j = j + 1
    WEND
    print r$
next
end
 
data "---------- Ice and Fire ------------"
data ""
data "fire, in end will world the say Some"
data "ice. in say Some"
data "desire of tasted I've what From"
data "fire. favor who those with hold I"
data ""
data "... elided paragraph last ..."
data ""
data "Frost Robert -----------------------"

Output:

------------ Fire and Ice ---------- 

Some say the world will end in fire, 
Some say in ice. 
From what I''ve tasted of desire 
I hold with those who favor fire. 

... last paragraph elided ... 

----------------------- Robert Frost 

Rust[edit]

const TEXT: &'static str = 
"---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------";
 
fn main() {
    println!("{}", 
             TEXT.lines() // Returns iterator over lines
             .map(|line|  // Applies closure to each item in iterator (for each line)
                  line.split_whitespace() // Returns iterator of words
                  .rev() // Reverses iterator of words
                  .collect::<Vec<_>>() // Collects words into Vec<&str>
                  .join(" ")) // Convert vector of words back into line
             .collect::<Vec<_>>() // Collect lines into Vec<String>
             .join("n")); // Concatenate lines into String
}

S-lang[edit]

variable ln, in =
  ["---------- Ice and Fire ------------",
   "fire, in end will world the say Some",
   "ice. in say Some",
   "desire of tasted I've what From",
   "fire. favor who those with hold I",
   "",
   "... elided paragraph last ...",
   "",
   "Frost Robert -----------------------"];

foreach ln (in) {
  ln = strtok(ln, " t");
  array_reverse(ln);
  () = printf("%sn", strjoin(ln, " "));
}
------------ Fire and Ice ----------
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Scala[edit]

Works with: Scala version 2.9.x

object ReverseWords extends App {

  """|  ---------- Ice and Fire ------------
     |
     |  fire, in end will world the say Some  
     |  ice. in say Some                      
     |  desire of tasted I've what From       
     |  fire. favor who those with hold I     
     |
     |  ... elided paragraph last ...         
     |
     |  Frost Robert -----------------------  """
    .stripMargin.lines.toList.map{_.split(" ")}.map{_.reverse}
    .map(_.mkString(" "))
    .foreach{println}
  
}
 ------------ Fire and Ice ----------

 Some say the world will end in fire,
 Some say in ice.
 From what I've tasted of desire
 I hold with those who favor fire.

 ... last paragraph elided ...

 ----------------------- Robert Frost

Scheme[edit]

(for-each
  (lambda (s) (print (string-join (reverse (string-split s #/ +/)))))
  (string-split
    "---------- Ice and Fire ------------

    fire, in end will world the say Some
    ice. in say Some
    desire of tasted I've what From
    fire. favor who those with hold I

    ... elided paragraph last ...

    Frost Robert -----------------------"
    #/[ r]*n[ r]*/))

Output:

------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

sed[edit]

#!/usr/bin/sed -f

G
:loop
s/^[[:space:]]*([^[:space:]][^[:space:]]*)(.*n)/2 1/
t loop
s/^[[:space:]]*//

Seed7[edit]

$ include "seed7_05.s7i";

const array string: lines is [] (
    "---------- Ice and Fire ------------",
    "",
    "fire, in end will world the say Some",
    "ice. in say Some",
    "desire of tasted I've what From",
    "fire. favor who those with hold I",
    "",
    "... elided paragraph last ...",
    "",
    "Frost Robert -----------------------");

const proc: main is func
  local
    var string: line is "";
    var array string: words is 0 times "";
    var integer: index is 0;
  begin
    for line range lines do
      words := split(line, ' ');
      for index range length(words) downto 1 do
        write(words[index] <& " ");
      end for;
      writeln;
    end for;
  end func;
------------ Fire and Ice ---------- 
 
Some say the world will end in fire, 
Some say in ice. 
From what I've tasted of desire 
I hold with those who favor fire. 
 
... last paragraph elided ... 
 
----------------------- Robert Frost 

SenseTalk[edit]

set poem to {{
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------
}}

repeat with each line in poem
	put (each word of it) reversed joined by space
end repeat
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Sidef[edit]

DATA.each{|line| line.words.reverse.join(" ").say};

__DATA__
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------

Smalltalk[edit]

poem := '---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I''ve what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------'.

(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' '  ]) joinUsing: (String cr).
'------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I''ve tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost'

Sparkling[edit]

This only considers space as the word separator, not tabs, form feeds or any other sort of whitespace. (This, however, turns out not to be an issue with the example input.)

let lines = split("---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------", "n");

foreach(lines, function(idx, line) {
	let words = split(line, " ");
	let reverseWords = map(words, function(idx) { return words[sizeof words - idx - 1]; });
	foreach(reverseWords, function(idx, word) {
		printf("%s ", word);
	});

	print();
});

Standard ML[edit]

val lines = [
  " ---------- Ice and Fire ------------ ",
  "                                      ",
  " fire, in end will world the say Some ",
  " ice. in say Some                     ",
  " desire of tasted I've what From      ",
  " fire. favor who those with hold I    ",
  "                                      ",
  " ... elided paragraph last ...        ",
  "                                      ",
  " Frost Robert ----------------------- "
]

val revWords = String.concatWith " " o rev o String.tokens Char.isSpace

val () = app (fn line => print (revWords line ^ "n")) lines

Swift[edit]

import Foundation

// convenience extension for better clarity
extension String {
    var lines: [String] {
        get {
            return self.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
        }
    }
    var words: [String] {
        get {
            return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        }
    }
}

let input = "---------- Ice and Fire ------------nnfire, in end will world the say Somenice. in say Somendesire of tasted I've what Fromnfire. favor who those with hold Inn... elided paragraph last ...nnFrost Robert -----------------------n"

let output = input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("n")

print(output)
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Tailspin[edit]

def input: ['---------- Ice and Fire ------------',
                    '',
                    'fire, in end will world the say Some',
                    'ice. in say Some',
                    'desire of tasted I''ve what From',
                    'fire. favor who those with hold I',
                    '',
                    '... elided paragraph last ...',
                    '',
                    'Frost Robert -----------------------']
;
 
composer words
  [ <word>* ]
  rule word: <~WS> <WS>?
end words
 
$input... -> '$ -> words -> $(last..first:-1)...;
' -> !OUT::write

Tcl[edit]

set lines {
    "---------- Ice and Fire ------------"
    ""
    "fire, in end will world the say Some"
    "ice. in say Some"
    "desire of tasted I've what From"
    "fire. favor who those with hold I"
    ""
    "... elided paragraph last ..."
    ""
    "Frost Robert -----------------------"
}
foreach line $lines {
    puts [join [lreverse [regexp -all -inline {S+} $line]]]
    # This would also work for data this simple:
    ### puts [lreverse $line]
}
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Alternatively…

Works with: Tcl version 8.6

puts [join [lmap line $lines {lreverse $line}] "n"]

TXR[edit]

Run from command line:

txr reverse.txr verse.txt

Solution:

@(collect)
@  (some)
@(coll)@{words /[^ ]+/}@(end)
@  (or)
@(bind words nil)
@  (end)
@(end)
@(set words @(mapcar (fun nreverse) words))
@(output)
@  (repeat)
@(rep)@words @(last)@words@(end)
@  (end)
@(end)

New line should be present after the last @(end) terminating vertical definition.
i.e.

not

UNIX Shell[edit]

while read -a words; do
    for ((i=${#words[@]}-1; i>=0; i--)); do
        printf "%s " "${words[i]}"
    done
    echo
done << END
---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some                   
desire of tasted I've what From   
fire. favor who those with hold I

... elided paragraph last ...       

Frost Robert ----------------------- 
END

Works with: ksh

Same as above, except change

to

VBA[edit]

Option Explicit

Sub Main()
Dim Lines(9) As String, i&
    'Input
    Lines(0) = "------------- Ice And Fire -------------"
    Lines(1) = ""
    Lines(2) = "fire, in end will world the say Some"
    Lines(3) = "ice. in say Some"
    Lines(4) = "desire of tasted I've what From"
    Lines(5) = "fire. favor who those with hold I"
    Lines(6) = ""
    Lines(7) = "... elided paragraph last ..."
    Lines(8) = ""
    Lines(9) = "Frost Robert -----------------------"
    'Output
    For i = 0 To 9
        Debug.Print ReverseLine(Lines(i), " ")
    Next
End Sub

Private Function ReverseLine(Line As String, Optional Separat As String) As String
Dim T, R, i&, j&, deb&, fin&
    If Len(Line) = 0 Then
        ReverseLine = vbNullString
    Else
        If Separat = "" Then Separat = " "
        T = Split(Line, Separat)
        ReDim R(UBound(T)): j = LBound(T)
        deb = UBound(T): fin = deb / 2
        For i = deb To fin Step -1
            R(j) = T(i)
            R(i) = T(j)
            j = j + 1
        Next i
        ReverseLine = Join(R, Separat)
    End If
End Function
------------- Fire And Ice -------------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

VBScript[edit]

Option Explicit

Dim objFSO, objInFile, objOutFile
Dim srcDir, line

Set objFSO = CreateObject("Scripting.FileSystemObject")

srcDir = objFSO.GetParentFolderName(WScript.ScriptFullName) & ""

Set objInFile = objFSO.OpenTextFile(srcDir & "In.txt",1,False,0)

Set objOutFile = objFSO.OpenTextFile(srcDir & "Out.txt",2,True,0)

Do Until objInFile.AtEndOfStream
	line = objInFile.ReadLine
	If line = "" Then
		objOutFile.WriteLine ""
	Else
		objOutFile.WriteLine Reverse_String(line)
	End If
Loop

Function Reverse_String(s)
	Dim arr, i
	arr = Split(s," ")
	For i = UBound(arr) To LBound(arr) Step -1
		If arr(i) <> "" Then
			If i = UBound(arr) Then
				Reverse_String = Reverse_String & arr(i)
			Else
				Reverse_String = Reverse_String & " " & arr(i)
			End If
		End If
	Next
End Function

objInFile.Close
objOutFile.Close
Set objFSO = Nothing

Output written to a file.

 ------------ Fire and Ice ----------

 Some say the world will end in fire,
 Some say in ice.
 From what I've tasted of desire
 I hold with those who favor fire.

 ... last paragraph elided ...

----------------------- Robert Frost

V (Vlang)[edit]

fn main() {
    mut n := [
        "---------- Ice and Fire ------------",
        "                                    ",
        "fire, in end will world the say Some",
        "ice. in say Some                    ",
        "desire of tasted I've what From     ",
        "fire. favor who those with hold I   ",
        "                                    ",
        "... elided paragraph last ...       ",
        "                                    ",
        "Frost Robert -----------------------",
    ]
    for i, s in n {
        mut t := s.fields() // tokenize
        // reverse
        last := t.len - 1
        for j, k in t[..t.len/2] {
            t[j], t[last-j] = t[last-j], k
        }
        n[i] = t.join(" ")
    }
    // display result
    for t in n {
        println(t)
    }
}

Simpler version:

mut n := [
  "---------- Ice and Fire ------------",
  "                                    ",
  "fire, in end will world the say Some",
  "ice. in say Some                    ",
  "desire of tasted I've what From     ",
  "fire. favor who those with hold I   ",
  "                                    ",
  "... elided paragraph last ...       ",
  "                                    ",
  "Frost Robert -----------------------",
]

println(
  n.map(
    it.fields().reverse().join(' ').trim_space()
  ).join('n')
)
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Wren[edit]

var  lines = [
    "---------- Ice and Fire ------------",
    "                                    ",
    "fire, in end will world the say Some",
    "ice. in say Some                    ",
    "desire of tasted I've what From     ",
    "fire. favor who those with hold I   ",
    "                                    ",
    "... elided paragraph last ...       ",
    "                                    ",
    "Frost Robert -----------------------"
]

for (line in lines) {
    var tokens = line.trim().split(" ")
    tokens = tokens[-1..0]
    System.print(tokens.join(" "))
}
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

XBS[edit]

func revWords(x:string=""){
	(x=="")&=>send x+"<br>";
	set sp = x::split(" ");
	send sp::reverse()::join(" ");
}
 
set lines:array=[
	"---------- Ice and Fire ------------",
	"",
	"fire, in end will world the say Some",
	"ice. in say Some",
	"desire of tasted I've what From",
	"fire. favor who those with hold I",
	"",
	"... elided paragraph last ...",
	"",
	"Frost Robert -----------------------",
];
 
foreach(v of lines){
	log(revWords(v));
}
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

XPL0[edit]

string 0;
def LF=$0A, CR=$0D;

proc Reverse(Str, Len); Reverse order of chars in string
char Str; int Len;
int  I, J, T;
[I:= 0;
J:= Len-1;
while I < J do
    [T:= Str(I);  Str(I):= Str(J);  Str(J):= T;
    I:= I+1;  J:= J-1;
    ];
];

char Str;
int  I, LineBase, WordBase;
[Str:= 
"---------- Ice and Fire ------------
 
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
 
... elided paragraph last ...
 
Frost Robert -----------------------";
I:= 0;
repeat  LineBase:= I;
        loop    [WordBase:= I;
                repeat I:= I+1 until Str(I) <= $20;
                Reverse(@Str(WordBase), I-WordBase);
                if Str(I)=CR or Str(I)=LF or Str(I)=0 then quit;
                I:= I+1;        skip space
                ];
        Reverse(@Str(LineBase), I-LineBase);
        while Str(I)=CR or Str(I)=LF do I:= I+1;
until   Str(I) = 0;
Text(0, Str);
CrLf(0);
]
------------ Fire and Ice ----------
 
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
 
... last paragraph elided ...
 
----------------------- Robert Frost

Yabasic[edit]

data "  ---------- Ice and Fire ------------  "
data "                                        "
data "  fire, in end will world the say Some  "
data "  ice. in say Some                      "
data "  desire of tasted I've what From       "
data "  fire. favor who those with hold I     "
data "                                        "
data "  ... elided paragraph last ...         "
data "                                        "
data "  Frost Robert -----------------------  "
data ""

dim w$(1)

do
    read l$
    if l$ <> "" then
        n = token(l$, w$(), " ")
        for i = n to 1 step -1
            print w$(i), " ";
        next
        print
    else
        break
    end if
loop

zkl[edit]

text:=Data(0,String,
#<<<
"---------- Ice and Fire ------------

fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I

... elided paragraph last ...

Frost Robert -----------------------");
#<<<

text.pump(11,Data,fcn(s){ // process stripped lines
   s.split(" ").reverse().concat(" ") + "n" })
   .text.print();
------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost

Problem Statement: Given a string s, reverse the words of the string.

Examples:

Example 1:
Input: s=”this is an amazing program”
Output: “program amazing an is this”

Example 2:
Input: s=”This is decent”
Output: “decent is This”

Solution:

DisclaimerDon’t jump directly to the solution, try it out yourself first.

Solution 1(Brute Force)

Intuition: We just need to print the words in reverse order. Can we somehow store them in reverse order of the occurrence and then simply add it to our answer?

Approach

  • Use a stack to push all the words in a stack
  • Now, all the words of the string are present in the stack, but in reverse order
  • Pop elements of the stack one by one and add them to our answer variable. Remember to add a space between the words as well. 
  • Here’s a quick demonstration of the same

Code:

C++ Code

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s="TUF is great for interview preparation";
    cout<<"Before reversing words: "<<endl;
    cout<<s<<endl;
    s+=" ";
    stack<string> st;
    int i;
    string str="";
    for(i=0;i<s.length();i++)
    {
        if(s[i]==' ')
        {
            st.push(str);
            str="";
        }
        else str+=s[i];
    }
    string ans="";
    while(st.size()!=1)
    {
        ans+=st.top()+" ";
        st.pop();
    }
    ans+=st.top();// The last word should'nt have a space after it
    cout<<"After reversing words: "<<endl;
    cout<<ans;
    return 0;
}

Output:

Before reversing words:
TUF is great for interview preparation
After reversing words:
preparation interview for great is TUF

Time Complexity: O(N), Traversing the entire string

Space Complexity: O(N), Stack and ans variable

Java Code

import java.util.*;
class Test
{
public static void main(String[] args)
{
	String s = "TUF is great for interview preparation";
	System.out.println("After reversing words: ");
	System.out.println(s);
	s += " ";
	Stack<String> st = new Stack<String>();
	int i;
	String str = "";
	for (i = 0;i < s.length();i++)
	{
		if (s.charAt(i) == ' ')
		{
			st.push(str);
			str = "";
		}
		else
		{
			str += s.charAt(i);
		}
	}
	String ans = "";
	while (st.size() != 1)
	{
		ans += st.peek() + " ";
		st.pop();
	}
	ans += st.peek(); // The last word should'nt have a space after it
	System.out.println("After reversing words: ");
	System.out.print(ans);
}
}

Output:

Before reversing words:
TUF is great for interview preparation
After reversing words:
preparation interview for great is TUF

Time Complexity: O(N), Traversing the entire string

Space Complexity: O(N), Stack and ans variable

Solution 2(Optimized Solution)

Intuition: Notice, that we are using a stack in order to perform our task. Can we somehow not use it and reverse the words as we move through the string? Could we store a word in reverse order when we are adding it to our answer variable?

Approach:

  • We start traversing the string from the end until we hit a space. It indicates that we have gone past a word and now we need to store it.
  • We check if our answer variable is empty or not
  • If it’s empty, it indicates that this is the last word we need to print, and hence, there shouldn’t be any space after this word.
  • If it’s empty we add it to our result with a space after it. Here’s a quick demonstration of the same

Code:

C++ Code

#include<bits/stdc++.h>
using namespace std;
string result(string s)
{
    int left = 0;
    int right = s.length()-1;
    
    string temp="";
    string ans="";
    
    //Iterate the string and keep on adding to form a word
    //If empty space is encountered then add the current word to the result
    while (left <= right) {
        char ch= s[left];
        if (ch != ' ') {
            temp += ch;
        } else if (ch == ' ') {
            if (ans!="") ans = temp + " " + ans;
            else ans = temp;
            temp = "";
        }
        left++;
    }
    
    //If not empty string then add to the result(Last word is added)
    if (temp!="") {
        if (ans!="") ans = temp + " " + ans;
        else ans = temp;
    }
    
    return ans;    
}
int main()
{
    string st="TUF is great for interview preparation";
    cout<<"Before reversing words: "<<endl;
    cout<<st<<endl;
    cout<<"After reversing words: "<<endl;
    cout<<result(st);
    return 0;
}

Output:

Before reversing words:
TUF is great for interview preparation
After reversing words:
preparation interview for great is TUF

Time Complexity: O(N), N~length of string

Space Complexity: O(1), Constant Space

Java Code

import java.io.*;
class Test
{
static private String result(String s)
{
	int left = 0;
	int right = s.length() - 1;

	String temp = "";
	String ans = "";

	//Iterate the string and keep on adding to form a word
	//If empty space is encountered then add the current word to the result
	while (left <= right)
	{
		char ch = s.charAt(left);
		if (ch != ' ')
		{
			temp += ch;
		}
		else if (ch == ' ')
		{
			if (!ans.equals(""))
			{
				ans = temp + " " + ans;
			}
			else
			{
				ans = temp;
			}
			temp = "";
		}
		left++;
	}

	//If not empty string then add to the result(Last word is added)
	if (!temp.equals(""))
	{
		if (!ans.equals(""))
		{
			ans = temp + " " + ans;
		}
		else
		{
			ans = temp;
		}
	}

	return ans;
}
public static void main(String[] args)
{
	String st = "TUF is great for interview preparation";
	System.out.println("Before reversing words: ");
    System.out.println(st);
    System.out.println("After reversing words: ");
	System.out.print(result(st));
}
}

Output:

Before reversing words:
TUF is great for interview preparation
After reversing words:
preparation interview for great is TUF

Time Complexity: O(N), N~length of string

Space Complexity: O(1), Constant Space

Special thanks to Naman Daga for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article


C program to reverse order of words in a given string – In this article, we will discuss the multiple methods to reverse the order of words in a given string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The methods used in the same are as follows:

  • Using Standard Method
  • Using Function

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

As given in the example in the uploaded image above, firstly, we need to enter a specific string.

The string uploaded is as follows:

“hello welcome to computer programming”

Thus, a completely reversed string of the same is as follows:

“programming computer to welcome hello”

Hence, the methods to do the same in C programming are as follows:

Using Standard Method

  1. Initialize k=0, j=0.

2) Read the entered string using gets(s). Initialize n=length of the string.

3) Swap the starting index element s[i] with the last index element s[n-i-1].Repeat this step using for loop for(i=0;i<n/2;i++).After all iterations of for loop, we will get reverse ordered string.

4) Insert the location values of the white spaces present in the string, in the array a[] using for loop for(i=0;s[i];i++) , by increasing i,k values.

After for loop initialize a[k] with i value.

5) Reverse the order of letters of each word in the reverse ordered string as

The outer for loop iterates with the structure for(i=0; i<=k;i++)

a) initialize n=a[i]-j.n indicates the length of the word.

b) The inner for loop iterates through the word with  the structure for(l=0;l<n/2;l++)

swap the element with starting index(l+j) with element with ending index (n-l-1) by increasing the l value.

Repeat a,b steps until i<=k.

6) Print the string with reverse order of words.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000];  

    int a[1000],i,n,k=0,j=0,l,temp;

    printf(«Enter  the string : «);

    gets(s);

    n=strlen(s);

    for(i=0;i<n/2;i++)  

    {

     temp=s[i];

s[i]=s[n1i];

s[n1i]=temp;

}

for(i=0;s[i];i++)

{

        if(s[i]==‘ ‘)

        {

  a[k++]=i;   

    }

    }

    a[k]=i;

    for(i=0;i<=k;i++)

{

n=a[i]j;

for(l=0;l<n/2;l++)

{

temp=s[l+j];

s[l+j]=s[a[i]1l];

s[a[i]1l]=temp;

}

j=a[i]+1;

}  

    printf(«n %s»,s);

    return 0;

}

Output:

Enter  the string: hello welcome to computer programming

programming computer to welcome hello

Using Function

  1. The swap(char *s1, char *s2) function swaps the character at the pointer variable s1 with the character at the pointer variable s2.

2) The stringlength(char *s) function will return the length of the given string.

3) The main() function calls the reverse(char *s) function, passing the string as an argument to the function. The reverse() function reverses the order of the words in the string.

4) The reverse() function calls the stringlength() function to get the length of the string and initialize the length value to n.

a) Calls the stringlength() function to get the length of the string and initialize the length value to n.

b) For loop iterates, through the string from i=0 to i<n/2.

It calls the swap() function to swap the element at starting index i with the element at last index (n-i-1).

The reverse function calls the swap function repeatedly until i<n/2.After all iterations of for loop, we will get the reverse ordered string.

c) It finds the locations of the white space in the string and stores the location values into the string a[] using for loop for(i=0;s[i];i++) and with increasing i, k values.

d) For loop iterates from i=0 to i<k

Initialize n with the length of the word.i.e a[i]-j.

The reverse function calls the swap function to swap the letter at the starting index (l+j) of the word with the letter at the last index (a[i]-l-1).

Initialize j=a[i]+1.

It calls the swap function repeatedly until i<k.

After all iterations of for loop, we will get the string with reverse ordered words.

5) Print the string with reverse order of words.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

#include <stdio.h>

#include <string.h>

swap(char *s1,char*s2)

{

char temp;

temp=*s1;

*s1=*s2;

*s2=temp;

}

int stringlength(char *s)

{

int i;

for(i=0;s[i];i++);

return i;

}

int reverse(char *s)

{

    int a[1000],i,n,k=0,j=0,l;

    n=stringlength(s);

    for(i=0;i<n/2;i++)  

    {

     swap(&s[i],&s[n1i]);

    }

for(i=0;s[i];i++)

{

        if(s[i]==‘ ‘)

        {

  a[k++]=i;   

    }

    }

    a[k]=i;

    for(i=0;i<=k;i++)

{

n=a[i]j;

for(l=0;l<n/2;l++)

{

swap(&s[l+j],&s[a[i]1l]);

        }

j=a[i]+1;

}  

}

int main()

{

    char s[1000];  

    printf(«Enter  the string : «);

    gets(s);

    reverse(s);

    printf(«n %s»,s);

}

Output:

Enter the string: hello welcome to computer programming

programming computer to welcome hello

Like this post? Please share to your friends:
  • Reverse word order in english
  • Reverse word in python
  • Reverse the word order
  • Reverse the text in word
  • Reverse the text in excel