2

I have an array of strings, and I want to delete a particular string from that array. How can I do that? My code is:

 private void nregexp(){
        String str_nregexp = i_exp_nregexp.getText();
        boolean b;
        for(int i=0; i<selectedLocations.length; i++){
            b=  selectedLocations[i].indexOf(str_nregexp) > 0;
            if(b){
                String i_matches = selectedLocations[i];
                ........
                ........
            }
        }
    }

I have to remove i_matches from selectedLocations.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Are you looking to search the array? Do you already know what the string is? Do you want the new array to be one element smaller? Do you want the array to be left with a hole? etc. – Smalltown2k Jul 15 '09 at 09:28
  • Duplicate http://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java – skaffman Jul 15 '09 at 13:06
  • http://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java – Ezombort Jul 15 '09 at 09:26

6 Answers6

2

I depends what you mean by "delete a particular String from an array". If you wish to remove its value, you can simply set its value to null, however if you mean actually remove that element from the array (you have an array of 5 elements and you want the result after deleting the element to be 4), this is not possible without copying the array with the item removed.

If you want this behavior, you might want to take a look at a dynamic list such as ArrayList or LinkedList

Edit: If you wanted a simple method to copy the array into an array with the String removed, you could do something like:

List<Foo> fooList = Arrays.asList(orgArray);
fooList.remove(itemToRemove);
Foo[] modifiedArray = fooList.toArray();
Kingamajick
  • 2,281
  • 1
  • 16
  • 19
1

You will need to copy the array to a smaller array, omitting the string you don't want. If this is a common situation, you should consider using something other than an array, such as LinkedList or ArrayList.

Kevin Peterson
  • 7,189
  • 5
  • 36
  • 43
1

If you really want to do it yourself, here is an example:

import java.util.Arrays;
public class DelStr {
    public static String[] removeFirst(String[] array, String what) {
        int idx = -1;
        for (int i = 0; i < array.length; i++) {
            String e = array[i];
            if (e == what || (e != null && e.equals(what))) {
                idx = i;
                break;
            }
        }
        if (idx < 0) {
            return array;
        }
        String[] newarray = new String[array.length - 1];
        System.arraycopy(array, 0, newarray, 0, idx);
        System.arraycopy(array, idx + 1, newarray, idx, array.length - idx - 1);
        return newarray;
    }
    public static void main(String[] args) {
        String[] strings = { "A", "B", "C", "D" };
        System.out.printf("Before: %s%n", Arrays.toString(strings));
        System.out.printf("After: %s%n", 
            Arrays.toString(removeFirst(strings, "D")));
    }
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192
0

Could you show us your code? Why don't you use ArrayList, as it has a remove(index) and remove(object) support?

Edit: Perhaps

private void nregexp() {
    String str_nregexp = i_exp_nregexp.getText();
    boolean b;
    List<String> list = new ArrayList<String>(Arrays.asList(selectedLocations)); 
    for(Iterator<String> it = list.iterator(); i.hasNext();){
        String e = it.next();
        b =  e.indexOf(str_nregexp) > 0;
        // b = e.matches(str_regexp); // instead?
        if(b){
            String i_matches = s;
            it.remove(); // we don't need it anymore
            ........
            ........
        }
    }
    selectedLocations = list.toArray(new String[list.size()]);
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192
0

You cannot change the length of the array, after initializing an array its length is set. So you cannot delete the element directly, you can only replace it, also with null.

String[] arr = new String[10];
// fill array
...
// replace the fifth element with null
arr[4] = null;

If you want to change the length of the Array you should try a list instead:

List<String> list = new ArrayList<String>();
// fill list
...
// remove the fifth element
list.remove(4);
Mnementh
  • 50,487
  • 48
  • 148
  • 202
0

I've reached this solution that allows you to remove all the elements that equal the removal element:

private static <T> T[] removeAll(T[] array, T element) {
    if (null == array)
        throw new IllegalArgumentException("null array");
    if (null == element)
        throw new IllegalArgumentException("null element");

    T[] result = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length);

    int j = 0;
    for (int i = 0; i < array.length; i++) {
        if (!element.equals(array[i]))
            result[j++] = array[i];
    }
    return Arrays.copyOf(result, j);
}

I also did some benchmarking and this solution is definitely better then using Lists. Although, if performance is not a problem here, I would use Lists.

If you really need to remove only one element (the first) @kd304 has the solution.

Community
  • 1
  • 1
bruno conde
  • 47,767
  • 15
  • 98
  • 117