5
I need to replace a character at a certain String position().
Example - Swap character[21] with 'X':
String Original = 01078989469150999134B B 2116456
Modified String = 01078989469150999134B X 2116456
I’m using the following code:
StringBuffer sb = new StringBuffer('01078989469150999134BB2116456');
sb.setCharAt(21, 'X');
String novaStr = sb.toString();
However, from what I read and understood, it is expensive to use Stringbuffer(), especially in this process, which will be used several times (barcode reading).
The question is - Is this method effective? Is there a better and more efficient way?
The class
AbstractStringBuilder
which is extended so much byStringBuffer
as perStringBuilder
internally uses an array ofchar
. So the efficiency is pretty much the same, except for the so-called method and the limit check. The only efficiency problem that there may be in some cases is whether routine convertString
from and toStringBuilder
at all times, that is, a bad implementation would create aStringBuilder
, change the character, run thetoString
and repeat this over and over again, instead of doing it in "batch".– utluiz
Thank you for your contribution, and forgive the ignorance: what would "do in batch"?
– electus
It was a short way of saying that all characters should be changed and only then the content should be converted to String. I wrote this way because the space of the commentary ended and I didn’t want to write 2... :S
– utluiz
Quiet. Grateful once again. =)
– electus