Java:从现有字符串数组中删除项

Java:从现有字符串数组中删除项,java,arrays,string,methods,Java,Arrays,String,Methods,我已经搜索了几个SOF线程,但似乎找不到我正在寻找的答案。它们中的大多数都提供了一个答案,代码超出了我到目前为止所学的范围 我尝试了很多不同的方法,但都不能按我所需要的方式工作 程序应该获取给定的数组,读取它,找到给定的toRemove项,然后重新打印没有toRemove项的数组。 我相信我的问题在removeFromArray方法中 public static void main(String[] args) { String[] test = {"this", "is", "th

我已经搜索了几个SOF线程,但似乎找不到我正在寻找的答案。它们中的大多数都提供了一个答案,代码超出了我到目前为止所学的范围

我尝试了很多不同的方法,但都不能按我所需要的方式工作

程序应该获取给定的数组,读取它,找到给定的toRemove项,然后重新打印没有toRemove项的数组。

我相信我的问题在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;
}
publicstaticvoidmain(字符串[]args)
{
String[]test={“this”、“is”、“the”、“example”、“of”、“the”、“call”};
String[]result=removeFromArray(测试“the”);
System.out.println(Arrays.toString(result));
}
公共静态字符串[]removeFromArray(字符串[]arr,字符串toRemove)
{
int newLength=0;
对于(int i=0;i
这是我的java课程中的一个作业,我们还没有学习列表(我在谷歌搜索中偶然发现的答案之一),所以这不是我的选择

现在,它应该输出: [例如,这是呼叫]

目前它正在输出:[例如,这是空的]


任何和所有的帮助将不胜感激

在第二个循环中需要两个索引,因为要迭代两个长度不同的数组(输入数组和输出数组)

此外,
newLength
是一个令人困惑的名称,因为它不包含新的长度。它包含输入数组长度和输出数组长度之间的差异。您可以更改其值以匹配其名称

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;
int newLength=arr.length;
对于(int i=0;i
以下代码删除所提供字符串的所有匹配项

注意,我添加了几行代码来验证输入,因为如果我们向您的程序传递空数组,它将失败。您应该始终验证代码中的输入

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;
}
public static String[]removeFromArray(String[]arr,String toRemove){
//验证输入非常重要
如果(arr==null){
抛出新的IllegalArgumentException(“无效输入!请重试”);
}
//计算toRemove字符串的出现次数。
//如果数组元素或toRemove为空,请使用Objects.equals。
int计数器=0;
对于(int i=0;i
您的代码中有@Eran指出的错误,可以解决您的问题。但我将讨论另一种方法

现在,您首先遍历整个数组以查找要删除的出现次数,然后遍历数组以删除它们。为什么不在数组上迭代,删除它们呢。(我知道,您的第一个循环帮助您确定输出数组的大小,但如果您使用一些
List
ArrayList
等,则不需要该循环。)

然后返回这个数组。请现场观看此方法。

尝试此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);
List test=Arrays.asList(“this”、“is”、“the”、“example”、“of”、“the”、“call”);
test.stream()
.filter(string->!string.equals(“the”))
.collect(收集器.toList())
.forEach(System.out::println);

您可以改用Java Stream,它将为您提供预期的结果,而且您的代码将更清晰、更小

看看下面我写的解决你问题的方法

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

如果您不熟悉java流,请查看

相同的差异,尽管这是一种更简单的方法。根据给定机器上读写的相对时间,OPs方法可能会更快。我认为不会。因为在OPs方法中,有一个
包含两个循环中的
操作。所花费的总时间为
(2*N*contains花费的时间)
N
为输入数组长度。但在这种方法中,它是
(包含所花费的N*时间)+(复制所花费的N*时间)
,而且
包含的操作比仅仅复制操作要昂贵得多。事实上,你是对的。实际上OP可能不应该使用
contains
,而是
等于
请注意,复制所需的时间实际上是
O(N)
,而不是真正的
N
,因为定期调整
数组列表的大小需要一些成本。是的,当然,我们不能忽略调整
ArrayList
对象大小的时间。isNull
主要用作筛选器谓词(例如
stream.filter(Objects::isNull).count()
。最好使用
arr==null
toRemove==null
作为
对象。isNull
只执行
==null
。此外,没有理由抛出
    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);
public static String[] removeFromArray(String[] arr, String toRemove) {
    return Arrays.stream(arr)
      .filter(obj -> !obj.equals(toRemove))
      .toArray(String[]::new);
}