Ant4res
Ant4res

Reputation: 1225

How to empty specific char array positions

I have a 200-elements-long char array, I load the vector with new characters in a loop, and at each cycle the element number can be different from the previous one, so how can I empty the unwanted position of the array? Note: the element size have to be of 200 and I can't resolve the problem creating a new instance of the object with new.

Thanks

Upvotes: 1

Views: 2718

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533550

If you are trying to delete characters, I would use a StringBuilder. This is more efficient than using a Vector.

char[] chars = new char[50];
Arrays.fill(chars, '-');

StringBuilder sb = new StringBuilder();
sb.append(chars);
// remove characters 10 to 15.
sb.delete(10, 15);
// remove a character
sb.deleteCharAt(24);
// replace some characters
sb.replace(30, 40, "Hello World");

System.out.println(sb);

prints

------------------------------Hello World----

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500953

Do you mean something like:

Arrays.fill(array, index, array.length, '\0');

? Of course, that will just overwrite the rest of the array with U+0000 values... there's no such thing as a char[] element being "empty". There will always be a char at every element in the array; U+0000 is one way of indicating "don't treat this as real data".

Upvotes: 3

Related Questions