Reputation:
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
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
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
Reputation: 2073
Just use a Stringbuilder
, append you text and call the reverse
method.
Upvotes: 0