K
K
kachurinets2018-03-22 00:51:04
JavaScript
kachurinets, 2018-03-22 00:51:04

How to reverse a string without using standard methods?

Tell me how to reverse a string without using standard methods, for example, reverse(), etc. Also, you do not need to use an array, additional variables. You just need to change the value of the string on the spot.
For example, an additional variable o is used here;

function reverse(s) {
  var o = '';
  for (var i = s.length - 1; i >= 0; i--)
    o += s[i];
  return o;
}

The additional variable is not used below, but this solution is not suitable, since the string is simply doubled and then reduced.
function reverse(s) {
  for (var i = s.length - 1; i >= 0; i--) {
    s+= s[i];
    }
  return s.substring(s.length/2);
}

Maybe there is another way to do this? For example, change the first and last character and so on until everything changes. How to implement it?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
0
0xD34F, 2018-03-22
@kachurinets

You just need to change the value of the string on the spot

Need? Impossible. Strings in JS are immutable:
var str = 'abc'
str[1] = '!'
console.log(str) // чё, ждали "a!c"? - а вот ни хрена, "abc"

A
Anton Shvets, 2018-03-22
@Xuxicheta

let str = 'abcdefg';
for (let i = 0; i < str.length; i ++) {
  str = str.slice(1, str.length - i) + str[0] + str.substr(str.length - i); 
}
console.log(str);

No variables, except for the loop counter. But in general, you don’t need
to write like that :)
str.split('').reverse().join('');

S
Stalker_RED, 2018-03-22
@Stalker_RED

UPD: suitable options:
https://jsfiddle.net/1mcLfbdh/
https://jsfiddle.net/tfyfdbch/
unsuitable:

let x = [];
'Hello world!'.split('').forEach(s => x = [s].concat(x))
console.log(x.join(''))
https://jsfiddle.net/e2x7c463/
lolo!
let x = '', i = 'hakuna Matata!'.split('')
while (x+= i.splice(-1, 1), i.length) {}
x+=i

console.log(x)
https://jsfiddle.net/dc9fkdot/
After that, any reduceRight, pop or unshift is even boring to use.

M
McBernar, 2018-03-22
@McBernar

Does recursion work for you?

function func(str) {
  if(str === '') {
    return '';
  }
  return func(str.substr(1)) + str.charAt(0);
}

D
dom1n1k, 2018-03-22
@dom1n1k

You can exchange the values ​​of two variables without using an intermediate using the bitwise xor operation.
Googling further :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question