Best Way to Reverse a String

What is the most efficient algorithm for reversing a String in Java?

You say you want to know the most efficient way and you don't want to know some standard built-in way of doing this. Then I say to you: RTSL (read the source, luke):

Check out the source code for AbstractStringBuilder#reverse, which gets called by StringBuilder#reverse. I bet it does some stuff that you would not have considered for a robust reverse operation.

Reverse a string in Java

You can use this:

new StringBuilder(hi).reverse().toString()

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

Best way to reverse a string

public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}

Fastest way to reverse a string in C

Maybe something like this?

char *str_reverse_in_place(char *str, int len)
{
char *p1 = str;
char *p2 = str + len - 1;

while (p1 < p2) {
char tmp = *p1;
*p1++ = *p2;
*p2-- = tmp;
}

return str;
}

Reverse a string in Python

Using slicing:

>>> 'hello world'[::-1]
'dlrow olleh'

Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, "repeatedly step from right to left by 1 character".

Is there a faster Reverse String Algorithm for JavaScript?

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.
Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.

Solution 1

function reverseString (str) {
return str.split('').reverse().join('')
}

console.time("function test");
reverseString('Hello') // => 0.250ms
console.timeEnd("function test");

Solution 2

function reverseString (str) {
let reversed = '';
for (const character of str) {
reversed = character + reversed
}
return reversed
}
console.time("function test");
reverseString('Hello') // => 0.166ms
console.timeEnd("function test");

Solution 3

function reverseString (str) {
return str.split('').reduce((reversed, character) => character + reversed, '')
}
console.time("function test");
reverseString('Hello') // => 0.133ms
console.timeEnd("function test");

In ES6, you have one more option

function reverseString (str) {
return [...str].reverse().join('')
}


Related Topics



Leave a reply



Submit