0
\$\begingroup\$

I'm new to Java and I want to know if this code is efficient, and if there a shorter and faster way to reverse a string.

package Excercises;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Please enter a string you want to reverse: ");
        String text = scan.next();
        String[] letters = text.split("");
        char[] reversed = new char[letters.length];
        int c = letters.length - 1;
        for(String s : letters) {
            reversed[c] = s.charAt(0);
            c = c - 1;
        }

        System.out.println(new String(reversed));
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ I sometimes give this task on interviews, with the condition that the code should use as less memory as possible and that reverse may not be used. \$\endgroup\$
    – lexicore
    Oct 11, 2014 at 9:02

1 Answer 1

7
\$\begingroup\$

is there a shorter and a faster way than below to reverse a string?

Sure,

new StringBuilder(string).reverse().toString()

is generally used. Here is code to reverse a string that's also quite nice and that might even be faster in some situations.

As to your code:

  • naming: avoid short variable names: c and s could be index and letter.
  • c = c - 1 is often written as c--.
  • you shouldn't just write your code in main, but in a function so that you can easily test it. And some unit test can never hurt.
  • your code throws a StringIndexOutOfBoundsException for the empty string.

is this code efficient?

No, not really. I profiled it, and the result is:

name                    per call (mean, ns)     per call (median, ns)     95th percentile (ns)     total (ms)     runs     
reverseCharToString     897                     892                       816                      5.7408         8000000  
reverseBuilder          132                     132                       101                      0.8448         8000000  
reverseArray            126                     125                       95                       0.8064         8000000 

Where reverseCharToString is your code, reverseBuilder is the code I pasted above, and reverseArray is the code I linked to. The main reason for this is that you are creating a lot of new objects.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.