简体   繁体   English

如何以特定方式反转字符串

[英]How to reverse a string in a specific way

This is a very specific question and I want to reverse a string in this way however I don't know how to go about it.这是一个非常具体的问题,我想以这种方式反转字符串,但我不知道如何去做。

What i want to do is take a word lets say 'hello'.我想做的是一句话让我们说“你好”。 olleh奥列

and take the first and last letters and output 'oellh' then doing the same thing for the next two characters so 'e' and 'l' which would then output 'olleh'.并取第一个和最后一个字母并输出“oellh”,然后对接下来的两个字符执行相同的操作,因此“e”和“l”将输出“olleh”。

So to summaries this I need to reverse the first and last character and then the same thing for the second characters until i get to the middle character.所以总结一下,我需要反转第一个和最后一个字符,然后对第二个字符进行相同的操作,直到我到达中间字符。

This must use a for loop.这必须使用 for 循环。

        reverse('hello');

    function reverse(string) {

        var character = [];

        for (var i = string.length -1; i >= 0; i--) {
            character.push(string[i]);
        }

        console.log(character.join(""));

    }

Let me know if this needs further explanation如果这需要进一步解释,请告诉我

This might do the trick:这可能会奏效:

function replaceAt(string, index, character){
    return string.substr(0, index) + character + string.substr(index+character.length);
}

function reverse(string) {
    var len = string.length;
    len = len/2;
    var s = string;

    for (var i = 0; i < len ; i++)
    {
        var m = s[string.length-i-1];
        var k = s[i];
        s = replaceAt(s,i, m);
        s = replaceAt(s, string.length-i-1, k);       
    }
       return s;

}

您可以轻松地反转字符串:

"hello".split("").reverse().join("")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM