2015-11-23 59 views
0

如果不使用分割反向和聯接函數,那麼會怎麼做這樣的事情?在不使用內置函數的情況下在字符串中反轉字符

鑑於問題:反轉的話在一個字符串 樣品輸入:「Hello World」的 輸出樣本:「世界你好」

<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> 
+3

[字符串中的反向詞]的可能的複製(http://stackoverflow.com/questions/2279344/reversing-words-in -a-string)根據評論不重複。 ***限制使用這些方法。這是一些釘子。去尋找一把螺絲刀把他們放在... *** – xQbert

+1

所以你需要避免使用'split'和'reverse'? – Ben

+0

@Ben Aston是的,它的約束條件之一 –

回答

0

以百萬計的不同的解決方案中,鍵入我的量最少可以拿出涉及使用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" 
0

你也可以去幻想和嘗試是這樣的:

我不能拿出一個更短的解決方案。

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

0

另一個想法用於反轉在一個字符串的話使用堆棧數據結構。像這樣:

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

數組可以像堆棧一樣使用。並且堆棧是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'); 
相關問題