我试图通过将现有的元素复制到一个新的数组中来删除数组中的空元素。然而,新数组的初始化导致我的返回值为null,即使我在for
循环中初始化它。
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;
}
发布于 2017-01-30 12:24:57
实际上我不确定你想要实现什么,但是如果你想从数组中移除一个空字符串,你可以在java8中使用streams和filters来实现,就像这样:
String[] objects = Arrays.stream(new String[]{"This","", "will", "", "", "work"}).filter(x -> !x.isEmpty()).toArray(String[]::new);
发布于 2017-01-30 12:41:32
数组是不可变的,因此大小保持不变,因此您需要创建一个新数组,因此,如果您根据旧数组的大小创建新数组,则仍将具有空元素
如果只想使用数组,则需要对数组中的非空元素进行计数,以获得新Array的大小。使用List/ArrayList更容易
public String[] wordsWithout(String[] words, String target) {
List<String> tempList=new ArrayList<String>();
for(int i = 0; i < words.length; i = i +1){
if (words[i]!=null||words[i].trim().length()>0){
tempList.add(words[i]);
}
}
return (String[]) tempList.toArray();
}
发布于 2017-01-30 12:26:53
要检查相等性,可以使用.equals()方法i-e string2 1.equals(String2),要检查不相等性,可以使用相同的方法,但不使用not(!)运算符i-e。!string2 1.equals(String2)。您应该在循环外部声明store数组,因为在每次迭代中,它都会在名为store的对象上创建一个新对象。在else条件中,执行storei = wordsi。
https://stackoverflow.com/questions/41935581
复制