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 excluding) then insert desired character at index
i then copy elements from index
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.
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.append(chars); sb.replace(2, 4, "L"); System.out.println(sb);
You can look at the code for replace to see how it does it.
Copy array portions with System.arraycopy() instead of iterating over its elements.
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.
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 Else arrayCopy(i) = arraySource(i) End If Next
ifcondition from index
n-1would not be better perhaps. Instead of this, i should prefer two
forloops (i mean
System.arraycopy) from index
i-1and from index
n-1respectively. This might increase the performance. Correct me if i am wrong - Ravi Joshi 2012-04-04 20:21