gpt4 book ai didi

java - 从数组中删除空元素(Java)

转载 作者:行者123 更新时间:2023-12-02 06:06:54 25 4
gpt4 key购买 nike

我试图通过将现有元素复制到新数组来从数组中删除空元素。但是,即使我在 for 循环中初始化新数组,它的初始化也会导致我的返回值为 null。

public String[] wordsWithout(String[] words, String target) {
for(int i = 0; i < words.length; i = i +1){
String store[] = new String[words.length];
if (words[i] == target){
words[i] ="";
}
else if(words[i] != target){
words[i] = store[i];
}
}
return words;
}

最佳答案

我实际上不确定你想要实现什么,但如果你想从数组中删除一个空字符串,你可以使用 java 8 中的流和过滤器来实现,如下所示:

String[] objects = Arrays.stream(new String[]{"This","", "will", "", "", "work"}).filter(x -> !x.isEmpty()).toArray(String[]::new);

关于java - 从数组中删除空元素(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com