此代码的目标是将字符串“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