Replacing two characters with one character in a char array

Go To


How to replace two characters with one character in a char array? Let me explain a bit more. I have a char array of length n . In this char array i want to replace two characters with one character in a specified index i. In this process the array length is going to decrease by 1.
The idea which i came to my mind is, first create a new char array of length n-1 then copy all elements from index 0 to index i (i excluding) then insert desired character at index i then copy elements from index i+2 (i including) to the index n-1. But this process require two times for loop. Is there any better approach which can do the same in efficient manner.

2012-04-04 19:42
by Ravi Joshi


Or a more efficient way of doing this is to use a StringBuilder which is a wrapper for char[] and let it do it for you.

char[] chars = "Hello".toCharArray();
StringBuilder sb = new StringBuilder();
sb.replace(2, 4, "L");



You can look at the code for replace to see how it does it.

2012-04-04 19:46
by Peter Lawrey
Can i create StringBuilder instance with a char array? I have char array in my hands - Ravi Joshi 2012-04-04 20:19


Copy array portions with System.arraycopy() instead of iterating over its elements.

2012-04-04 19:45
by ahanin


Given that you want a new array object, there's no faster way than by copying each array element once, so there's no more efficient method than this. If you use two calls to System.arraycopy(), you don't have to write the loops yourself.

If you don't need a new array object, you could just move the higher-numbered array elements down by one, which involves just half the number of copies -- but then you're going to need to keep track of the length some other way.

2012-04-04 19:46
by Ernest Friedman-Hill
Okay...i get it here Thank you so much - Ravi Joshi 2012-04-04 19:49


It could use a single for loop. Just put in an IF statement indicating if iteration (i) = index you want to replace then do a different operation rather than just copy.

Written in basic:

For i = 0 to n - 1
       If i = x then
             arrayCopy(i) = replaceChars
             arrayCopy(i) = arraySource(i)
       End If
2012-04-04 19:50
by kazmone1
checking every time an if condition from index 0 to index n-1 would not be better perhaps. Instead of this, i should prefer two for loops (i mean System.arraycopy) from index 0 to index i-1 and from index i+1 index n-1 respectively. This might increase the performance. Correct me if i am wrong - Ravi Joshi 2012-04-04 20:21
ArrayCopy is better all around since can be done with two lines of code. Just was pointing out could be done with single loop - kazmone1 2012-04-04 21:55