[英]Java ArrayList - Replace a specific letter or character within an ArrayList of Strings?
我正在嘗試替換/刪除字符串 ArrayList 中的某些字符。這是我已經嘗試過的代碼:
for (int i = 0; i < newList.size(); i++) {
if (newList.get(i).contains(".")) {
newList.get(i).replace(".", "");
}
}
我嘗試遍歷 ArrayList,如果任何元素包含“.”,則將其替換為空。 例如,如果我的 ArrayList 中的一個詞是“Works.”,那么結果 output 將是“Works”。 不幸的是,該代碼段似乎無法正常運行。 我做了一些類似的事情來刪除任何包含數字的元素並且它工作正常,但是我不確定在僅替換 String 中的單個字符同時仍然保留 ArrayList 元素時是否需要使用特定的語法或方法。
newList.get(i).replace(".", "");
這不會更新列表元素 - 您構建了替換的字符串,但隨后丟棄了該字符串。
你可以使用set
:
newList.set(i, newList.get(i).replace(".", ""));
或者您可以使用ListIterator
:
ListIterator<String> it = newList.listIterator();
while (it.hasNext()) {
String s = it.next();
if (s.contains(".")) {
it.set(s.replace(".", ""));
}
}
但更好的方法是使用replaceAll
,無需顯式循環:
newList.replaceAll(s -> s.replace(".", ""));
也不需要檢查contains
:如果搜索字符串不存在, replace
將不會執行任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.