【发布时间】:2016-08-29 01:19:14
【问题描述】:
所以我们有以下内容:
ArrayList<String> list = ( new ArrayList<String>( ) );
list.add( new String( "hello" ) ); // add first word at position [0]
list.add( new String( "world" ) ); // add second word at position [1]
我不想使用 .replace 方法,因为它会替换所有的出现。假设我只想修改 hello 单词中的第一个“l”并将其更改为“x”,我该怎么做?我只想定位数组中字符串中的特定元素#。
System.out.println( list ); // display the full arraylist
初始输出:
[hello, world]
期望的输出:
[hexlo, world]
【问题讨论】:
-
我们可以看看你尝试了什么代码吗?
-
不要将
new String()用于字符串文字。您正在无缘无故地创建一个额外的对象。 -
您可以使用
replaceFirst()方法或使用StringBuilder代替String并使用setCharAt()方法。 -
除了过时的
new String(…)创建;您不需要将new ArrayList<String>()放在大括号中。 -
我认为问题是关于使用列表,而不仅仅是替换字符串中的字符......它绝对不是这两个答案的完全重复......你必须考虑到你无法“就地”更改字符串,因此您必须管理列表元素的添加和删除
标签: java string arraylist replace