I’ve got a char array called encoded which has a series of char values. I want to insert 3 chars into the middle of the array and keep the remaining chars by pushing them to the next spaces. Is this possible?
Portion of the code I’ve used as follows just inserts and replaces the next two chars too.
encoded = new char[20];
encoded = encodeArray.toCharArray();
for (int x = 0; x < encoded.length; x++) {
if (encoded[x] == a) {
encoded[x] = amp;
} if (encoded[x] == und) {
for (int y = 0; y < 3; y++) {
encoded[x+y] = tilde;
}
}
}
Any direction would be greatly appreciated.
Several points.
First, Java’s arrays a relatively low-level data structures. They don’t support insertion, etc. And they don’t dynamically grow.
In your case, you can manually shift the characters by
n, but that is loss-less only if the original array had extranslots of capacity.For manipulating character arrays, look at
java.lang.StringBuilderFinally, since we are talking Java, there are certain Unicode codepoints that require two Java
chars. One of the many reasons to use higher level operations when manipulating character sequences.