删除字符串arraylist java中的元素

大家好,我是使用Java的新手,我只是将一个字符串列表放置在一个数组列表中,我想删除以下每个字符串中的某些元素


ArrayList<String> data = new ArrayList<String>();



data.add( "ksh10,000"); 

data.add( "ksh20,000");  

data.add( "ksh30,000");

data.add( "ksh40,000");

data.add( "ksh50,000');

所以我想删除字符串之间的“ ksh”和逗号,以便得到像


10000,20000,30000,40000,50000

我尝试了什么


for (int i = 0; i < data.lenght(); i++ ) {

    data.set(i, data.get(i).replace("ksh", ""));

    data.set(i, data.get(i).replace(",",""));

}

。在此先感谢您的帮助。


叮当猫咪
浏览 226回答 3
3回答

收到一只叮咚

如果您要做的只是更改数据中的值,请遍历每个元素并使用以下replace方法:for (int i = 0; i < data.size(); i++ ) {&nbsp; &nbsp; data.set(i, data.get(i).replace("ksh", ""));&nbsp; &nbsp; data.set(i, data.get(i).replace(",",""));}这将用空字符串替换“ ksh”字符串和逗号。正如Snoob所说,replace()由于String是不可变的,因此只返回新的String。

慕田峪4524236

public class Main {public static void main(String[] args) {&nbsp; &nbsp; ArrayList<String> list = new ArrayList<>();&nbsp; &nbsp; list.add( "ksh10,000");&nbsp; &nbsp; list.add( "ksh20,000");&nbsp;&nbsp; &nbsp; list.add( "ksh30,000");&nbsp;&nbsp; &nbsp; list.add( "ksh40,000");&nbsp;&nbsp; &nbsp; list.add( "ksh50,000");&nbsp;&nbsp; &nbsp; printStrings(list);&nbsp; &nbsp; ArrayList<String> newList = editList(list);&nbsp; &nbsp; printStrings(newList);}public static ArrayList<String> editList(ArrayList<String> list){&nbsp; &nbsp; ArrayList<String> newList = new ArrayList<>();&nbsp; &nbsp; for(String str : list) {&nbsp; &nbsp; &nbsp; &nbsp; String temp = "";&nbsp; &nbsp; &nbsp; &nbsp; for(char c : str.toCharArray()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(Character.isDigit(c))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp += c;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; newList.add(temp);&nbsp; &nbsp; }&nbsp; &nbsp; return newList;}public static void printStrings(ArrayList<String> list) {&nbsp; &nbsp; for(String str : list){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str);&nbsp; &nbsp; }}}最好的方法(如果您不知道字符串的确切结构)是检查字符是否为数字,如果是,则将其添加到字符串中,为列表中的每个字符串循环并返回一个新的字符串。 list,其中包含第一个列表中字符串的编辑版本。

ABOUTYOU

这是使用StreamAPI的巨大变化。我将把练习的一部分留给您作为练习。import java.util.stream.*;class Solution {&nbsp;String generateOutput (ArrayList<String> inputValues) {&nbsp;&nbsp; return data.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(this::scrubValue)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.joining(","));}String scrubValue (String input) {&nbsp; // you'll need to write code here that takes an input like "ksh10,000" and returns "10000"}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java