在不使用内置函数的情况下反转字符串JS中的单词

Reversing words in a string JS without using built in function

如果不使用split reverse和join功能,怎么会做这样的事情?

给出的问题:反转字符串中的单词 示例输入:"Hello World" 示例输出:"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>

在数百万种不同的解决方案中,我能想出的最少的输入涉及使用 lastIndexOfsubstring

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

输出:

"fox  brown  quick The"

你也可以尝试这样的事情:

我想不出更短的解决方案。

  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);

另一种反转字符串中单词的想法是使用 Stack 数据结构。像这样:

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);

数组可以像开箱即用的堆栈一样使用。而栈是后进先出的,这正是你所需要的。

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');

或者使用调用栈作为你的栈:

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');

javascript 中最简单的方法。这里 replace() 有 /,/g 它将把字符串中的所有逗号替换为 space.

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

;