0

I need to have my code output the String in reverse order. For example, the output should have "code" return as "edoc". This is what I have done so far.

public String reverseString(String str) {
 String res = "";

for (int i = 0; i <= str.length()-1; i++) {
   res = res + str.charAt(i);
 }
  return res;
}
4
  • Does this HAVE to use a for loop? Is this java, c# or what? Commented Mar 31, 2017 at 19:32
  • Sorry. It's in Java, and yes it has to use a for loop. Commented Mar 31, 2017 at 19:42
  • OK just as a comment, non-for new StringBuilder(mystring).reverse().toString() Commented Mar 31, 2017 at 19:44
  • Pick and understand the technique in an answer that augments your "learning" exercise; either a positive or negative for loop. Commented Apr 3, 2017 at 17:54

2 Answers 2

2

The main issue with your way of doing it is your taking the n'th character from str and appending it to make it the n'th character of res.

You could fix it like this:

public String reverseString(String str) {
   String res = "";

   for (int i = str.length() - 1; i >= 0; i--) {
       res = res + str.charAt(i);
   }
   return res;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You have your concatenation backwards. Try:

public String reverseString(String str) {
    String res = "";
    for (int i = 0; i < str.length(); i++) {
       res = str.charAt(i) + res;            // Add each char to the *front*
    }
    return res;
}

Note also the simpler, canonical, loop termination condition.

Comments