此代碼的目標是將字符串「A Happy」更改爲「Hippy」。使用字符數組打印字符串而不是創建新的字符串對象
String originalStr = "A Happy";
char[] charOriStr = originalStr.toCharArray();
charOriStr[3] = 'i'; //simplified code, we are supposed to loop through the String
要打印修訂字符串,我用:
System.out.println(charOriStr);
但是推薦解如下:
String revised = new String(charOriStr);
System.out.println(revised);
我是一個初學者,我不知道,如果我應該按照推薦的解決方案作爲最佳實踐指南?在此欣賞一些指導,謝謝。
爲什麼不使用'String'中的'replaceAll'方法? – Jobin
'for(char ch:charOriStr)System.out.print(ch); System.out.println();' –
在你的第一個代碼片段中,'revised'沒有被定義。如果你直接通過'System.out.println(修改)'來關注它,'你會看到一個錯誤,說'修改'是未知的 – Aaron