my assignment question is like that
Write a program which prints the letters in a char array in reverse order using
void printReverse(char
public void printReverse(char[] word){
reverseWordMaxIndex = word.length -1;
char[] reverseWord = new char(reverseWordMaxIndex + 1)
for ( int i= 0; i < word.length; i++){
reverseWord[reverseWordMaxIndex-i] = word[i];
}
for( int i= 0; i < reverseWord.length; i++){
System.out.println(reverseWord[i]);
}
}
This is a class which reveres the character array using recursion.
public class ReverseString {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = new String("Hello");
char[] strcharArray = str.toCharArray();
printReverse(strcharArray);
}
private static void printReverse(char [] str) {
helper(0, str);
}
private static void helper(int index, char [] str) {
if (str == null || index >= str.length) {
return;
}
helper(index + 1, str);
System.out.println(str[index]);
}
}
You can make use of StringBuilder#reverse() method like this:
String reverse = new StringBuilder(new String(letters)).reverse().toString();
This should take about 6 ms. It reverses a char array "in-place" before printing.
public static void reverseString(char[] s) {
int len = s.length;
if (len == 0)
return;
for (int i=0; i < (len/2); i++)
{
char l = s[i];
s[i] = s[len-i-1];
s[len-i-1] = l;
}
System.out.println(s);
}