What is the best way to replace a character in a given String position?

5

I need to replace a character at a certain position in String ().

Example - Change character [21] to 'X':

Original String = 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();

But for what I read and understood, getting to use StringBuffer () is expensive, 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?

    
asked by anonymous 01.08.2014 / 20:56

3 answers

5

There are three class options for handling Strings: String, StringBuffer, and StringBuilder.

Use:

  • String: when you do not want to be modifying the text a lot;
  • StringBuilder when you want to make numerous changes to the text.
  • StringBuffer when you want to make numerous modifications to the text and that the variable is thread safe.

So, the most efficient class to make modifications is the StringBuilder, however you should not opt for it if you are using the same variable for different threads at the same time, which is the case if you choose StringBuffer.

If this were to be done only once in the middle of your code, efficiency is something that matters little. So any of the choices would not change much.

As you said you are doing the operation for countless times, use the StringBuilder. The syntax is the same, see the example:

StringBuilder s = new StringBuilder("01078989469150999134BB2116456");
s.setCharAt(21, 'X');
System.out.println(s.toString());
    
01.08.2014 / 21:15
3

An alternative would be to use StringBuilder instead of StringBuffer , since the second uses synchronized methods and the first does not, and as it is known, method synchronization affects performance, since only one thread accesses at a time each method. What would the code look like:

StringBuilder sb = new StringBuilder("01078989469150999134BB2116456");
sb.setCharAt(21, 'X');
String novaString = sb.toString();
System.out.println(novaString);

Another alternative would be to not use either StringBuilder or StringBuffer , I just will not know about the performance issue:

String codigo = "01078989469150999134BB2116456";
char[] codigoChar = codigo.toCharArray();
codigoChar[21] = 'X';
codigo = String.valueOf(codigoChar);
System.out.println(codigo);
    
01.08.2014 / 21:14
0

In general I use StringBuilder:

var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "ZX");
theString = aStringBuilder.ToString();
    
01.08.2014 / 22:34