Java char Array - deleting elements

In Java you can't delete elements from an array. But you can either:

Create a new char[] copying only the elements you want to keep; for this you could use System.arraycopy() or even simplerArrays.copyOfRange(). For example, for copying only the first three characters of an array:

char[] array1 = {'h','m','l','e','l','l'};
char[] array2 = Arrays.copyOfRange(array1, 0, 3);

Or use a List<Character>, which allows you to obtain a sublist with a range of elements:

List<Character> list1 = Arrays.asList('h','m','l','e','l','l');
List<Character> list2 = list1.subList(0, 3);

Java function to remove a character from a character array:

String msg = "johnny can't program, he can only be told what to type";
char[] mychararray = msg.toCharArray();
mychararray = remove_one_character_from_a_character_array_in_java(mychararray, 21);
System.out.println(mychararray);

public char[] remove_one_character_from_a_character_array_in_java(
                           char[] original, 
                           int location_to_remove)
{
    char[] result = new char[original.length-1];
    int last_insert = 0;
    for (int i = 0; i < original.length; i++){
        if (i == location_to_remove)
            i++;

        result[last_insert++] = original[i];
    }
    return result;
}

The above method prints the message with the index 21 removed. You could place this in a loop to remove multiple items. Technically you are not deleting an item, you are creating a brand new char array with the item removed. You have to step through the entire string for each remove which is very inefficient.

Delete a character by index from a character array with StringBuilder in Java:

String mystring = "inflation != stealing";
char[] my_char_array = mystring.toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(mystring);
sb.deleteCharAt(10);
my_char_array = sb.toString().toCharArray();
System.out.println(my_char_array);             //prints "inflation = stealing"

The above code removes the exclamation mark from the character array. If you want to delete a RANGE of characters, use sb.delete(10, 15);

Tags:

Java

Arrays

Char