I think here is the code to better understand the program
-----------------------------------------------------------------------------
String textString = "Hello World" ;
String revString = "" ;
for(int i = textString.length() -1 ; i >= 0 ; i--)
{
revString = revString + textString.charAt(i);
}
System.out.println(revString);
-----------------------------------------------------------------------------
Output will be: dlroW olleH
2007-11-13 14:14:00
·
answer #1
·
answered by AgilePro 3
·
0⤊
1⤋
I give you 2 examples of code wich works and a couple of advices.
1) Never perform operation which alter a string by adding a character or remove one on strings. String in Java is an unmutable object which means that each change will create a new string, this can lead you to out of memory errors and poor performance quite easily. Use StringBuffer(s) or char arrays as you see best fit and then convert them into a string.
Naturally when you deal with a string such as "hello!" you can cope with it", but if you try it on somthing like an HTML page, 64kb for example, you will probably either crash the java VM or have the garbage collector running 99% of your CPU for a couple of minutes.
2) Never use recurrency if you have a viable alternative, recurrency is a fast way to StackOverflow and infinite loops problems. If you have tried the function Andy gave you you had expirienced it. Recurrency is cool, but dangerous, difficult to mantain and resource greedy, you must be quite skilled to use it, not for the faint of heart.
private static String reverse(String foo) {
char[] inArr = foo.toCharArray();
char[] outArr = new char[inArr.length];
int len = inArr.length;
for (int i = 0; i < len; i++) {
outArr[len-i-1] = inArr[i];
}
String bar = new String(outArr);
return bar;
}
private static String reverseComplex(String foo) {
char[] arr = foo.toCharArray();
int halfLen = (arr.length)/2;
int len = arr.length;
for(int i=0;i
char c= arr[i];
arr[i]=arr[len-i-1];
arr[len-i-1]=c;
}
String bar = new String(arr);
return bar;
}
2007-11-14 06:19:34
·
answer #2
·
answered by minus71 2
·
0⤊
0⤋
sure...remember a string is just an array of characters. so, use a for loop and start from the end and concatenate it to another temp string
String x = HELLO
temp += x.charAt(i);
2007-11-13 21:43:43
·
answer #3
·
answered by ? 6
·
0⤊
0⤋
Use it:
public static String reverse(String text) {
if (text.length() == 0) return "";
else return (reverse(text) + text.charAt(0);
}
2007-11-13 21:48:18
·
answer #4
·
answered by Andy T 7
·
0⤊
1⤋