0
\$\begingroup\$

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

""
"abcdef"
"abbbba"
null

I haven't been able to handle these conditions however

escape characters

"\n"
"\t"

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

special characters such as

áe

code:

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);
        count++;
    }
    return new String(strArr);
}
\$\endgroup\$
1
  • \$\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\$ Mar 13, 2014 at 8:36

2 Answers 2

3
\$\begingroup\$

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.

\$\endgroup\$
3
  • 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
    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
    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\$ Mar 13, 2014 at 8:38
0
\$\begingroup\$

A little suggestion. Instead of

if (len <= 0) {

I'd write

if (str.isEmpty()) {

because it's more readable.

Available since Java 1.6.

\$\endgroup\$

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.