javascript - Reverse words(not letters) for a string without using .reverse() - Stack Overflow

The problem I am working on asks for me to write a function reverseMessage() that takes a string messag

The problem I am working on asks for me to write a function reverseMessage() that takes a string message and reverses the order of the words in place.

The answer I first came up with works but apparently doesn't meet the requirements of this task:

function reverseMessage(string) {
    return string.split(" ").reverse().join(" ");
}

For example:

var string = "reversed are string your in words the now"
var results = "now the words in your string are reversed"

New solution:

I would like to split this string into an array and then loop through that array and swap the 1st index with the last index, the 2nd index with second to last index, 3rd index with the 3rd to last index, etc... until I meet in the middle.

I am trying to make the two different functions below work:

 function reverseMessage(string) {
     var array = string.split(" ");
     //loop through array and replace first index with last index, second   
     index with second to last index, third index with third to last index, etc
     for (var i = 0; i < array.length/2; i++) {
         for (var j = (array.length-1); j > array.length/2; j--) {
             array[i] = array[j];
             array[j] = array[i];
             messageSplit.join(",");
     }
 };



 function reverseMessage2(string) {
     var array = string.split(" ");
     var newArray = []
     for (var i = 0; i < array.length/2; i++) {
         newArray.unshift(array[i]++);
         newArray.join(",");
         return newArray;
     }
 };

Am I on the right track?

The problem I am working on asks for me to write a function reverseMessage() that takes a string message and reverses the order of the words in place.

The answer I first came up with works but apparently doesn't meet the requirements of this task:

function reverseMessage(string) {
    return string.split(" ").reverse().join(" ");
}

For example:

var string = "reversed are string your in words the now"
var results = "now the words in your string are reversed"

New solution:

I would like to split this string into an array and then loop through that array and swap the 1st index with the last index, the 2nd index with second to last index, 3rd index with the 3rd to last index, etc... until I meet in the middle.

I am trying to make the two different functions below work:

 function reverseMessage(string) {
     var array = string.split(" ");
     //loop through array and replace first index with last index, second   
     index with second to last index, third index with third to last index, etc
     for (var i = 0; i < array.length/2; i++) {
         for (var j = (array.length-1); j > array.length/2; j--) {
             array[i] = array[j];
             array[j] = array[i];
             messageSplit.join(",");
     }
 };



 function reverseMessage2(string) {
     var array = string.split(" ");
     var newArray = []
     for (var i = 0; i < array.length/2; i++) {
         newArray.unshift(array[i]++);
         newArray.join(",");
         return newArray;
     }
 };

Am I on the right track?

Share Improve this question edited Aug 28, 2015 at 10:59 TZHX 5,38816 gold badges49 silver badges58 bronze badges asked Aug 28, 2015 at 4:39 CrystalCrystal 1,5052 gold badges24 silver badges35 bronze badges 2
  • array[i] = array[j]; array[j] = array[i]; isn't going to "work" because you just replaced array[i] with array[j]! – RobG Commented Aug 28, 2015 at 4:48
  • Yeah I figured- just not sure how to write it correctly- thought I would write down somewhat of an idea of what I would like to happen hoping others could see what I was trying to acplish. – Crystal Commented Aug 28, 2015 at 4:53
Add a ment  | 

7 Answers 7

Reset to default 4
   function reverseMessage(string) {
     var array = string.split(" ");
     var result="";
     for (var i = array.length-1; i >=0; i--) {
         result+=array[i]+" ";
     }
    console.log(result);
 };

So in yours reverseMessage function You are trying to swap variable for that you are doing

array[i] = array[j]; array[j] = array[i];

Which is giving array[i]=array[j] so let say array[i]="This" and array[j]="That"so according to yours code array[i] will be "That" and array[j] will also be "That" so you can try something like this:

 function reverseMessage(string) {
     var array = string.split(" ");
     //loop through array and replace first index with last index, second
     //index with second to last index, third index with third to last index, etc
     for (var i = 0,j=(array.length)-1; i < array.length/2; i++) {
             temp=array[i]
             array[i] = array[j];
             array[j]=array[i]
             array[j] = temp; j--;}
       console.log(array.join(" "));
 };  reverseMessage("find you will pain only go you recordings security the into if");

try this one

function reverseMessage( str ) {

    var arrStr = [];
    var temp ="";
    for(var i = 0 ; i < str.length ; i++)
    {
        if(str[i] === " ")
        {
            arrStr.push(temp);
            temp="";
        }
        else
        {
            temp += str[i]; 
        }
    }
    if(temp.length >= 0)
    {
        arrStr.push(temp);
    }
    var result = "";
    for(var x=arrStr.length-1 ; x >=0 ; x--)
    {
        result += " "+arrStr[x];
    }
    return result;
}


console.log(reverseMessage("I am here"));

Well, someone's gotta do it:

function rev(s){
  var a = s.split(/ /),
      l = a.length;
      i = l/2 | 0;
  while (i--) a.splice(i, 1, a.splice(l-1-i, 1, a[i])[0]);
  return a.join(' ');
}

    document.write(rev('0 1 2 3 4 5 6 7 8 9'));

Using Array.split(), Array.pop(), Array.push() and String.substr():

var flip = function(str) {
  var res = "", sp = " ",  arr = str.split(sp);
  while (arr.length)
    res += arr.pop() + sp;
  return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));

Using String.lastIndexOf() and String.substr():

var flip = function(str) {
  var res = "", i, sp = ' ';
  while (str) {
    i = str.lastIndexOf(sp);
    res += str.substr(i + 1) + sp;
    str = str.substr(0, i);
  }
  return res.substr(0, res.length - 1); //remove last space
};

alert(flip("reversed are string your in words the now"));

What you want to do is split the words message into individual strings reverse them and then add them together, that will reverse them in place. Try

function reverseMessage(message){
  var reversedMessage = ''; //A string to hold the reversed message
  var words = message.split(' ');
  for(var i =0; i< words.length; i++){
     reversedMessage +=  reverse(words[i]) + " ";// add the reversed word to the reversed message, with a space at the end so the words dont touch
  }
  return reversedMessage
}
//A helper function that reverses a string
function reverse(s) {
  var o = '';
  for (var i = s.length - 1; i >= 0; i--)
    o += s[i];
  return o;
}

sources: http://eddmann./posts/ten-ways-to-reverse-a-string-in-javascript/

with `pop()` ;)

function reverseMessage(string) {
         var array = string.split(" ");
         var result="";
         while (array.length > 0) {
             result += array.pop()+" ";
         }
        console.log(result);
     };

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744799206a4594389.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信