2016-03-08 27 views
1

倒車字符串可以做到通過反向循環中將原始字符串(從str.length-1-> 0)字符串在Java中:功能的charAt使用

但爲什麼這工作不正常: 通過將字符從最後一位加到第0位:

int i = 0; 
while(i<originalStr.length()) 
{ 
    strRev.charAt(i)=originalStr.charAt(str.length()-1-i); 
    i++; 
} 
+5

您不能編輯在Java中的字符串,字符串是unmodifable – Ferrybig

+1

你應該看看StringBuilder類,如果你想編輯字符串:http://docs.oracle.com/javase/8/docs/ API/JAVA/LANG/StringBuilder.html。它有一個'setCharAt'方法,這似乎是你想要的。 – Henrik

回答

7

字符串在Java中是不可變的。你不能編輯它們。

如果您想爲訓練目的反轉字符串,您可以創建char[],對其進行操作,然後從char[]實例化String

如果你想扭轉爲專業用途的字符串,你可以這樣說:

2
strRev.charAt(i) // use to Retrieve what value at Index. Not to Set the Character to the Index. 

所有我們知道String是Java中的immutable類。每次如果您嘗試修改任何String對象,它都會創建一個新對象。

eg :- String abc = "Vikrant"; //Create a String Object with "Vikrant" 

     abc += "Kashyap"; //Create again a new String Object with "VikrantKashyap" 
          // and refer to abc again to the new Object. 
     //"Vikrant" Will Removed by gc after executing this statement. 

更好地使用StringBufferStringBuilder執行反向操作。這兩個類之間的唯一區別是

A)StringBuffer的是線程安全(同步)。有點慢,因爲每次需要檢查線程鎖定。

B)StringBuider不是線程安全的。所以,它給你更快的結果因爲它不是Synchronized

有幾家第三方罐,提供您喜歡Reverse和多串基地操縱Methods

import org.apache.commons.lang.StringUtils; //Import Statement 

String reversed = StringUtils.reverse(words); 
0

在您的測試方法的特點,最好的做法是使用三A模式:
安排所有必要的先決條件和投入。
就被測物體或方法採取行動。
斷言預期的結果已經發生。

@Test 
public void test() { 
    String input = "abc"; 

    String result = Util.reverse(input); 

    assertEquals("cba", result); 
}