2014-04-05 102 views
1

我相信我們可以使用for循環來反轉Java中的字符串。就像下面這樣:使用鏈接列表或數組來顛倒Java中的字符串?

String[] name = new String[10]; 

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

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

} 

但是另一個實現是使用LinkedList。所以我的理解是在客戶端不確定字符串數組可能動態增加多長時使用LinkedList。那是對的嗎?

+5

何時使用鏈接列表的數組列表http://stackoverflow.com/questions/393556/when-to-use-a-linked-list-over- an-array-array-list –

+1

通過字符反轉字符串將不適用於BMP以外的Unicode代碼點! – fge

+2

這是一個字符串數組,而不是一個字符串......您按照相反的順序在數組中打印字符串。 – CMPS

回答

0

可以使用鏈接的字符列表來做到這一點。

在這個實例中,將數組列表看作一個數組長度不限的數組。對於這一點,而不是增加值到數組的結尾,我們將它們添加到鏈表

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); 
} 

只要你有更多的字符添加到它,只需使用linkedList.addFirst()來的開始追加到開頭。