0

I am trying to write a simple method that reverse the characters of a string. I need someone to help me correct this.

public String backward(String s){
        String str=new String();
        String str2=s;
        char[] c=str.toCharArray();
        for (int i=c.length-1;i>=0;i--)
            str+=c[i];
        return str;
    }
  • 1
    https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=reverse%20order%20of%20string%20java and make sure you use something like a `StringBuilder` – Carlos Bribiescas Oct 28 '14 at 18:07
  • details. What are your errors? – scrappedcola Oct 28 '14 at 18:08
  • 1
    possible duplicate of [Reverse a string in Java](http://stackoverflow.com/questions/7569335/reverse-a-string-in-java) – Chiseled Oct 28 '14 at 18:12
  • And also get rid of i >= 0 in for loop. This should be i > -1. Reason: i >= 0 takes 3 operations, i > 0 ?, i == 0 ? and logical OR for the 2 results; i > -1 is just a single operation. – Trunk Oct 29 '18 at 20:56

5 Answers5

2

You can use StringBuilder's built-in reverse() method and then print the output. The method will iterate through each word in the source string, reverse it. For example:

import java.util.Scanner;
Scanner newStrng = new Scanner(System.in);
String reverString = new StringBuilder(newStrng).reverse.toString();
System.println.out(reverString);
newDevGeek
  • 363
  • 2
  • 18
1

Change

char[] c=str.toCharArray();

to

char[] c=s.toCharArray();
Alex
  • 627
  • 3
  • 12
  • 32
1

char[] c=str2.toCharArray();

str2, not str

or just s

smith
  • 194
  • 3
  • 15
0

Just use a Stringbuilder, append you text and call the reverse method.

Hannes
  • 2,018
  • 25
  • 32
0

You could make use of the String objects "charAt" method:

String str = "hello world";
String newString = "";
for(int i = 1; i <= str.length(); i++){
newString += str.charAt(str.length() - i);
}
System.out.println(newString);
Bryan
  • 1,938
  • 13
  • 12