如果不使用拆分反向和连接功能,人们将如何做这样的事情?
给出的问题:反转字符串中的单词Sample Input:“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>
反转String中单词的另一个想法是使用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);
你也可以尝试这样的东西:
我无法想出一个更短的解决方案。
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);
数组可以像开箱即用的堆栈一样使用。堆栈是LIFO,这是你需要的。
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');
在数百万种不同的解决方案中,我能想出的最少的打字量包括使用lastIndexOf
和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
输出:
"fox brown quick The"
在javascript中最简单的方法。这里的replace()有/,/ g它会将字符串中的所有逗号替换为空格。
var msg = 'Hello world I am Programmer';
var newstr = msg.split(" ").reverse().join().replace(/,/g, ' ');
console.log(newstr)
;