简体   繁体   中英

How to remove certain elements from my array in my Java code

I am working on the following coding prompt for my class: Your task is to write a method with the following signature:

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

The method should return a string array that has the same contents as arr, except without any occurrences of the toRemove string. For example, if your method is called by the code below

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

it should generate the following output:

[this, is, example, of, call]

Note: Your method will be passed values for arr and toRemove by the testing program – you should not read these values in from the user inside your method. Also, you must write this method with the signature requested above in order to receive credit. You do not need to write the code that calls the method – only the method itself. Hint: Because you must specify the length of an array when you create it, you will likely need to make
two loops through the input array: one to count the number of occurrences of the toRemove string so
that you can create the new array with the proper size and a second to copy all of the other strings to the new array.

I have everything working in my code but the last part where I have to print out the new array does not work, I know I have make it smaller so it will print out properly, but I can't get that part to work. I know I have to get rid of the null, but I don't know how. Also my code has to work for any array not just the test case I have. Some help or advice would really be nice. Thank you very much!!! :) Here is my code:

public static void main(String[] args) {
    String[] test = {"this", "is", "the", "example", "of", "the", "call"};
    String[] remove = removeFromArray(test, "the");
    System.out.println(Arrays.toString(remove));
}

public static String[] removeFromArray(String[] arr, String toRemove) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i].equals(toRemove)) {
            count++;
        }
    }

    String[] result = new String[arr.length - count];
    //for (int i = 0; i < arr.length; i++) {
    //  if(!arr[i].equals(toRemove)){
    //    result[].equals(arr[i]);
    //}

    //}
    return result;
}

you approach looks ok, it looks like the commented code yor are trying to assign the new array with the wrong emthod

you should use result[i] = arr[i] ; instead of result[].equals(arr[i]);

do at the end:

String[] result = new String[arr.length - count];
int k = 0;
for (int i = 0; i < arr.length; i++) {
    if(!toRemove.equals(arr[i])){
       result[k] =  arr[i];
       k++;
    }

}
return result;

Your last part should be assigning the value to the array one by one.

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

It's asking you to return a new String array which excludes the given word. Loop through the array and add word which does not equal to the given word.

public static String[] removeFromArray(String[] arr, String toRemove){
    ArrayList<String> words = new ArrayList<>();
    for(String s : arr)
        if(!s.equals(toRemove))
            words.add(s);
    return words.toArray(new String[0]);
}

Since array size cannot be changed after being created, use an ArrayList to store the words, then return as an array.

I know you're new to programming itself, so the solutions given are perfectly fine.

However, using Java, you'd usually use the libraries; in this case, the Collections library. If you're using Java 8, this is how you would do it:

public static String[] removeFromArray(String[] arr, String toRemove) {
    // create a List and fill it with your items
    ArrayList<String> list = new ArrayList();
    Collections.addAll(list, arr);

    // remove the items that are equal to the one to be removed
    list.removeIf(s -> toRemove.equals(s));

    // transfer back to array
    return list.toArray(new String[list.size()]);
}

Then, there are Java 8 Streams, which would make this

public static String[] removeFromArray(String[] arr, String toRemove) {
    return Arrays.stream(arr)             // create stream from array
        .filter(s -> !toRemove.equals(s)) // filter out items
        .toArray(String[]::new);          // create array from stream
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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