user7767103
user7767103

Reputation:

How to make a reverse string using a for loop?

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;
}

Upvotes: 0

Views: 36888

Answers (2)

Bohemian
Bohemian

Reputation: 425003

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.

Upvotes: 1

Jack Gore
Jack Gore

Reputation: 4252

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;
}

Upvotes: 2

Related Questions