简体   繁体   English

Java:从现有的String Array中删除一个项目

[英]Java: Remove an item from existing String Array

I've scoured a couple of the SOF threads but can't seem to find the answer I'm looking for. 我已经搜索了几个SOF线程,但似乎无法找到我正在寻找的答案。 Most of them provide an answer with code that's beyond the scope of what I have learned thus far. 他们中的大多数提供的代码答案超出了我迄今为止学到的范围。

I've tried quite a few different things and can't get this to work the way I need it to. 我已经尝试了很多不同的东西,并且无法按照我需要的方式使用它。

The program is supposed to take the given array, read it, find the given toRemove item, and re-print the array without the toRemove item. 该程序应该采用给定的数组,读取它,找到给定的toRemove项,并在没有toRemove项的情况下重新打印数组。

I believe my issue is within the removeFromArray method 我相信我的问题在removeFromArray方法中

public static void main(String[] args) 
{

    String[] test = {"this", "is", "the", "example", "of", "the", "call"};
    String[] result = removeFromArray(test, "the");
    System.out.println(Arrays.toString(result));
}

public static String[] removeFromArray(String[] arr, String toRemove)
{
    int newLength = 0;
    for(int i = 0; i < arr.length; i++)
    {    
        if(arr[i].contains(toRemove))
        {
            newLength++;
        }
    }
    String[] result = new String[arr.length-newLength];
    for(int i = 0; i < (result.length); i++)
    {
        if(arr[i].contains(toRemove))
        {

        }
        else
        {
            result[i] = arr[i];
        }
    }
    return result;
}

This is an assignment in my java class and we have not learned Lists (one of the answers I stumbled upon in my googling) yet so that is not an option for me. 这是我的java课程中的一项任务,我们还没有学习列表(我在谷歌搜索中偶然发现的答案之一),但这对我来说不是一个选择。

As it is now, it should be outputting: [this, is, example, of, call] 就像现在一样,它应该输出: [this,is,example,of,call]

Currently it is outputting: [this, is, null, example, of] 目前正在输出: [this,is,null,example of of]

Any and all help will be much appreciated! 任何和所有的帮助将不胜感激!

You need 2 indices in the second loop, since you are iterating over two arrays (the input array and the output array) having different lengths. 在第二个循环中需要2个索引,因为您正在迭代两个具有不同长度的数组(输入数组和输出数组)。

Besides, newLength is a confusing name, since it doesn't contain the new length. 此外, newLength是一个令人困惑的名称,因为它不包含新的长度。 It contains the difference between the input array length and the output array length. 它包含输入数组长度和输出数组长度之间的差异。 You can change its value to match its name. 您可以更改其值以匹配其名称。

int newLength = arr.length;
for(int i = 0; i < arr.length; i++)
{    
    if(arr[i].contains(toRemove))
    {
        newLength--;
    }
}
String[] result = new String[newLength];
int count = 0; // count tracks the current index of the output array
for(int i = 0; i < arr.length; i++) // i tracks the current index of the input array
{
    if(!arr[i].contains(toRemove)) {
        result[count] = arr[i]; 
        count++;
    }
}
return result;

The following code removes all occurrences of the provided string. 以下代码删除所有提供的字符串。

Note that I have added few lines for validate the input, because if we pass a null array to your program, it would fail. 请注意,我添加了几行来验证输入,因为如果我们将null数组传递给您的程序,它将失败。 You should always validate the input in the code. 您应该始终验证代码中的输入。

public static String[] removeFromArray(String[] arr, String toRemove) {

    // It is important to validate the input
    if (arr == null) {
        throw new IllegalArgumentException("Invalid input ! Please try again.");
    }

    // Count the occurrences of toRemove string.
    // Use Objects.equals in case array elements or toRemove is null.
    int counter = 0;
    for (int i = 0; i < arr.length; i++) {
        if (Objects.equals(arr[i], toRemove)) {
            counter++;
        }
    }

    // We don't need any extra space in the new array
    String[] result = new String[arr.length - counter]; 
    int resultIndex = 0; 

    for (int i = 0; i < arr.length; i++) {
        if (!Objects.equals(arr[i], toRemove)) {
            result[resultIndex] = arr[i];
            resultIndex++;
        }
    }

    return result;
}

There's the error that @Eran pointed out in your code, which can solve your problem. @Eran在您的代码中指出了错误,这可以解决您的问题。 But I'm going to discuss another approach. 但我要讨论另一种方法。

For now, you're first iterating over the entire array to find the number of occurrences to remove, and then, you're iterating over the array to remove them. 现在,您首先遍历整个数组以查找要删除的事件数,然后,您将遍历数组以删除它们。 Why don't you just iterate over the array, just to remove them. 你为什么不迭代数组,只是为了删除它们。 (I know, your first loop is helping you to determine the size of the output array, but you don't need that if you use some List like ArrayList etc.) (我知道,你的第一个循环正在帮助你确定输出数组的大小,但如果使用像ArrayList这样的List等,你就不需要了。)

List<String> resultList = new ArrayList<String>();
for(int i = 0; i < arr.length; i++)
{
    if(!arr[i].contains(toRemove))
    {
        resultList.add(arr[i]);
    }
}

And you can return the resultList , but if you really need to return an array, you can convert the resultList to an array like this: 并且您可以返回resultList ,但是如果您确实需要返回一个数组,则可以将resultList转换为resultList数组:

String [] resultArray = resultList.toArray(new String[resultList.size()]);

And then return this array. 然后返回此数组。 See this approach live here on ideone . 在ideone上看到这种方法。

Try this Java8 version 试试这个Java8版本

    List<String> test = Arrays.asList("this", "is", "the", "example", "of", "the", "call");

    test.stream()
        .filter(string -> !string.equals("the"))
        .collect(Collectors.toList())
        .forEach(System.out::println);

You can use Java Stream instead, it will give you the expected result and also your code will be clearer and really smaller. 您可以使用Java Stream,它会为您提供预期的结果,而且您​​的代码也会更清晰,更小。

See the method below I wrote that solves your problem. 请参阅我写的解决您问题的方法。

public static String[] removeFromArray(String[] arr, String toRemove) {
    return Arrays.stream(arr)
      .filter(obj -> !obj.equals(toRemove))
      .toArray(String[]::new);
}

If you're unfamiliar with java Stream, please see the doc here 如果您不熟悉java Stream,请参阅此处doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM