How to reverse the sequence of words in a sentence ?

5.12K viewsProgramming
0

For eg:- Input is “This is a test”
Output should be:- “Test a is this”

How to write a program for this ?

Changed status to publish
0

fs = require('fs')
fs.readFile('path to input file', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
    var list_of_strings = data.split("\n"),
 result = '', num = 1;
    for (var index = 1; index < list_of_strings.length; index++) {
  if(list_of_strings[index] && list_of_strings[index].trim()) {
   reverse(list_of_strings[index]);
  }
 }
 console.log(result);
 fs.writeFile("path to output file", result, function(err) {
    if(err) {
        return console.log(err);
    }
  console.log("The file was saved!");
 }); 
   function reverse (str) {
  if (str) {
   var minLength = str.length/2,
    start = 0,
    end = str.length - 1,
    output = '';
    str = str.split(/[ ]+/);
   for (var index = str.length-1; index >= 0; index--) {
    output += str[index] + " ";
   }
       result = result + "Case #"+num+': '+output + "\r\n";
   num++;
  }
 }
 });

Answered question
0

Loop through split strings by space and push to string array in reverse order

Answered question
Write your answer.

Categories