user4147700
user4147700

Reputation:

java-reversing order of characters in string

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

Upvotes: 0

Views: 159

Answers (5)

Bryan
Bryan

Reputation: 2088

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

Upvotes: 0

newDevGeek
newDevGeek

Reputation: 373

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

Upvotes: 2

smith
smith

Reputation: 186

char[] c=str2.toCharArray();

str2, not str

or just s

Upvotes: 1

Alex
Alex

Reputation: 667

Change

char[] c=str.toCharArray();

to

char[] c=s.toCharArray();

Upvotes: 1

Hannes
Hannes

Reputation: 2073

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

Upvotes: 0

Related Questions