Reversing words in a string JS without using built in function

不打扰是莪最后的温柔 提交于 2019-12-23 04:54:31

问题


Without using the split reverse and join functions, how would one do such a thing?

The Problem Given: Reverse the words in a string Sample Input: "Hello World" Sample Output: "World Hello"

<script>
  var newString = ""; 
  var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)"); 

  newString = theString.split(" ").reverse().join(" ")


  document.write(newString);
</script>

回答1:


Another idea for reversing the words in a String is using a Stack data structure. Like so:

var newString = "";
var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)");

var word = "";
var c;
var stack = [];
for (var i = 0, len = theString.length; i < len; i++) {
  c = theString[i];
  word += c;

  if (c == " " || i == (len-1)) {
      word = word.trim();
      stack.push(word);
      word = "";
  }  
}

while (s = stack.pop()) {    
    newString += s + " ";
}

console.log(newString);



回答2:


You could also go fancy and try something like this:

I couldn't come up with a shorter solution.

  var newString = "";
  var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)");

  theString.replace(/[^\s]*/g, function (value) {
      newString = value + ' ' + newString;
  });

  document.write(newString);



回答3:


Arrays can be used like stacks out of the box. And stacks are LIFO, which is what you need.

function reverseWords(str) {
    var word, words, reverse;

    words = str.match(/(?:\w+)/g);
    reverse = '';
    while(word = words.pop()) {
      reverse += word + ' ';
    }

    return reverse.trim();
}

reverseWords('hello world');

Or use the call stack as your stack:

function reverseWords(str) {
  var result = '';
  (function readWord(i = 0) {
    var word = '';
    if(i > str.length) {
        return '';
    }    
    while(str[i] !== ' ' && i < str.length) {
      word += str[i];
      i++;
    }    
    readWord(++i); // Skip over delimiter.
    result += word + ' ';    
  }());
  return result.trim();
}

reverseWords('hello world');



回答4:


Of the millions of different solutions, the least amount of typing I could come up with involves using lastIndexOf and substring.

var str = "The quick brown fox",
    reversed = "",
    idx;

while(true) {
    idx = str.lastIndexOf(" ")
    reversed = reversed + str.substring(idx).trim() + " "
    if (idx < 0) break;
    str = str.substring(0, idx)
}
reversed.trim()  # Oh, yes, trim too

Output:

"fox  brown  quick The"



回答5:


The simplest way to do in javascript. Here replace() have /,/g it will replace all comma from the string to space.

    var msg = 'Hello world I am Programmer';
    var newstr = msg.split(" ").reverse().join().replace(/,/g, ' ');
    console.log(newstr)

;



来源:https://stackoverflow.com/questions/33877226/reversing-words-in-a-string-js-without-using-built-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!