1

I believe that we can use a for loop to reverse a string in Java. Just like below:

String[] name = new String[10];

for(int i = name.length; i >0; i--){

    System.out.print(name[i-1]);

}

But another implementation is using LinkedList. So my understanding is to use LinkedList when the client is not sure how long the string array might increase dynamically. Is that correct?

The Third
  • 785
  • 2
  • 10
  • 30
  • 5
    when-to-use-a-linked-list-over-an-array-array-list http://stackoverflow.com/questions/393556/when-to-use-a-linked-list-over-an-array-array-list – Raul Guiu Apr 05 '14 at 17:22
  • 1
    Reversing a string character by character will not work for Unicode code points outside the BMP! – fge Apr 05 '14 at 17:25
  • 2
    This is an array of strings and not a string ... you are printing the strings in the array in the reverse order. – CMPS Apr 05 '14 at 17:26
  • Agree @AmirBawab tha makes sense. – The Third Apr 05 '14 at 17:30
  • You've got two off-by-one errors in this code. Remember that array indexes start at 0! The first is that the first index you'll access is `name[name.length]`, which will throw an `ArrayIndexOutOfBoundsException`. For instance, if `name` has three elements, then `name.length == 3` but its indexes are `0`, `1`, `2` -- _not_ `3`. The second error is that you only iterate while `i > 0`, which means you'll never access `name[0]` (the first element in the array). – yshavit Apr 05 '14 at 17:58
  • Good one @yshavit . Thanks I have made the changes. – The Third Apr 06 '14 at 17:59

1 Answers1

0

A linked list of characters can be used to do this.

In this instance, think of an array list as an array with unlimited length. For this, instead of adding values to the END of the array, we will add them to the BEGINNING of the linked list

LinkedList<Character> linkedList = new LinkedList<Character>();
String str = "Hello World";

for (int i = 0; i < str.length(); i++) {
    linkedList.addFirst(str.charAt(i));
}

//whenever it is time to print the value....
for (char c : linkedList) {
    //Print it out, one character at a time
    System.out.print(c);
}

Whenever you have to add more characters to it, just use linkedList.addFirst() to append it to the beginning.