April 4th, 2013, 02:24 PM
-
Reversing a string
HI! guys could anyone help me how do I print a reversed string using char array I mean I tried to convert a string to char array and I was trying to convert again that char array into a string but I am not able to do it. Below is the code which i tried
public class ArrayStrings {
String a;
int temp=0;
public void methodA(String a)
{
this.a=a;
char [] x= a.toCharArray();
System.out.println("the char of string is:");
for(int i=x.length-1;i>=0;i--)
{
System.out.println("the reverse order of string is:"+x[i]);
char [] b = {x[i]};
String str = new String(b);
System.out.println("the string is" +str);
}
}
public static void main(String[] args)
{
ArrayStrings res = new ArrayStrings();
res.methodA("hello");
}
}
April 4th, 2013, 03:56 PM
-
This line
make b a one character array.
April 4th, 2013, 04:50 PM
-
hi
i did not understand what you said could you explain it clearly
April 4th, 2013, 06:35 PM
-
Originally Posted by sravan18
i did not understand what you said could you explain it clearly
I mean that in that one line of code, all you are doing is creating a one element array. Each time that line is executed, you create a new array whose one element is the element at index i in the array x.
April 6th, 2013, 12:36 PM
-
Originally Posted by bullet
I mean that in that one line of code, all you are doing is creating a one element array. Each time that line is executed, you create a new array whose one element is the element at index i in the array x.
Do you HAVE to use an array?
Maybe use a StringBuilder? You're nearly there. Count backwards through the String getting each character & adding it to the new string.
Here's an example I knocked up with a StringBuilder.
Code:
String strNormal = "Hello";
StringBuilder oBuilder = new StringBuilder();
// Get length of string
int iStringLength = strNormal.length()-1; // -1 because characters in String are 0 referenced.
// Count backwards through the string
while (iStringLength >= 0)
{
oBuilder.append(strNormal.charAt(iStringLength));
iStringLength--;
}
System.out.println("Reversed String (expecting - olleH): " + oBuilder.toString());
You could also count forwards through the string and add to the string builder at position zero each time... but in terms of readability I think counting backwards is better because it follows the logic of what you're trying to achieve.