【问题标题】:Modify specific characters within String ArrayList [duplicate]修改String ArrayList中的特定字符[重复]
【发布时间】: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&lt;String&gt;() 放在大括号中。
  • 我认为问题是关于使用列表,而不仅仅是替换字符串中的字符......它绝对不是这两个答案的完全重复......你必须考虑到你无法“就地”更改字符串,因此您必须管理列表元素的添加和删除

标签: java string arraylist replace


【解决方案1】:

例如,您可以像这样使用list.set() 方法:

list.set(index, list.get(index).modifyingStringMethodhere());

根据您的需要修改字符串非常简单,java 原生支持大量工具。

【讨论】:

  • modifyingStringMethodhere 在任何地方都不存在
猜你喜欢
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2012-10-04
  • 1970-01-01
相关资源
最近更新 更多