V
V
Vladimir2017-08-10 12:00:23
JavaScript
Vladimir, 2017-08-10 12:00:23

How to reverse a string in half a loop?

Tell me, How to reverse a string in half a loop pass, without using built-in functions, str.split('').reverse().join('') - not suitable, you need "Hands". I understand how to turn over in a full pass, but this is not what is needed.

for(let i=(string.length-1); i>=0; i--){
            str2 += string[i];
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kulaeff, 2017-08-10
@zhuravlev125

There are about a dozen ways to reverse a string, one of which is recursion.

var str = 'chupacabra';

function reverse(str) {
  if (str.length === 0) return '';

  var
    s1 = str[0],
    s = str.slice(1, str.length - 1),
    s2 = str[str.length - 1]
    
  return s2 + reverse(s) + s1
}

console.log(reverse(str))

In this example, the string is reversed in 5 passes
https://jsfiddle.net/zxe296y9/1/

D
Dmitry Eremin, 2017-08-10
@EreminD

Offhand, yes

for(let i=(string.length-1); i>=((string.length-1) / 2); i--){
   let a = string[i]
   let b = string[string.length-1]
   let c = a
   a = b
   b = c
}

Those. in one revolution, swap the extreme elements

V
Victor L, 2017-08-10
@Fzero0

function revStr(str){
  return (str === '')?'':revStr(str.substr(1)) + str[0];
}
console.log(revStr('pepsi'));
//-------
var str = 'abcdef';
alert('\u202E'+str);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question