I am trying to create a method that reverses a string that will handle every case. So far the cases I have come up with are


I haven't been able to handle these conditions however

escape characters


Not sure how to make \n or \t into a string

special characters such as



public static String reverseStr(String str) {
    if ( str == null ) {
          return null;
    int len = str.length();
    if (len <= 0) {
        return "";
    char[] strArr = new char[len];
    int count = 0;
    for (int i = len - 1; i >= 0; i--) {
        strArr[count] = str.charAt(i);
    return new String(strArr);
  • \$\begingroup\$ We can review your code, but questions about how you can add a new feature to your code is not the topic of this site. \$\endgroup\$ Commented Mar 13, 2014 at 8:36

2 Answers 2


There is a good overview of string reversal algorithms in this answer. It should explain how special characters like é can be handled. I don't see what's your problem with "\n" and "\t". These are strings already.

  • 1
    \$\begingroup\$ Sorry I should have been a bit more specific. I wanted to handle inputs when \n is given by someone with out any programming experience whatsoever and expect `n` to be returned not a newline. \$\endgroup\$
    – Liondancer
    Commented Mar 13, 2014 at 6:50
  • 1
    \$\begingroup\$ How does that someone enter \n? Does he edit source code or provide input on CLI? If the former is true, leave a comment, otherwise I think his or her input will not be interpreted anyway. \$\endgroup\$
    – mkalkov
    Commented Mar 13, 2014 at 6:58
  • \$\begingroup\$ @Liondancer If \n is a special case and should only return a normal n, that should be handled before reversing the string IMO. Be aware though that \n is just the programmatic way of writing ASCII number 10 (line feed). \$\endgroup\$ Commented Mar 13, 2014 at 8:38

A little suggestion. Instead of

if (len <= 0) {

I'd write

if (str.isEmpty()) {

because it's more readable.

Available since Java 1.6.


Your Answer

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

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