I need to reverse the string of a user\'s input.
I need it done in the simplest of ways. I was trying to do reverseOrder(UserInput) but it wasn\'t working.
There is an interesting method to do it so too.
String input = "abc";
//Here, input is String to reverse
int b = input.length();
String reverse = ""; // Declaring reverse String variable
while(b!=0){
//Loop for switching between the characters of the String input
reverse += (input.charAt(b-1));
b--;
}
System.out.println(reverse);
I prefer using Apache's commons-lang for this kind of thing. There are all kinds of goodies, including:
StringUtils.reverse("Hello World!");
yields: !dlroW olleH
StringUtils.reverseDelimited("Hello World!", ' ');
yields: World! Hello
If you are new to programming, which I guess you are, my suggestion is "Why use simple stuff?". Understand the internals and play some!!
public static void main(String[] args) {
String str = "abcasz";
char[] orgArr = str.toCharArray();
char[] revArr = new char[orgArr.length];
for (int i = 0; i < orgArr.length;i++) {
revArr[i] = orgArr[orgArr.length - 1 - i];
}
String revStr = new String(revArr);
System.out.println(revStr);
Without going through the char sequence, easiest way:
public String reverse(String post) {
String backward = "";
for(int i = post.length() - 1; i >= 0; i--) {
backward = backward + post.substring(i, i + 1);
}
return backward;
}
new StringBuilder(str).reverse().toString()
java.util.Collections.reverseOrder
is for sorting in reverse of normal order.
public String reverseString(final String input_String)
{
char temp;
char[] chars = input_String.toCharArray();
int N = chars.length;
for (int i = 0 ; i < (N / 2) ; i++)
{
temp = chars[i];
chars[i] = chars[N - 1 - i];
chars[N - 1 - i] = temp;
}
return new String(chars);
}
Run :
Pandora
arodnaP