How to concatenate using StringBuilder?

0

I have the following method toString of a class

public String toString(){
   return  "Solicitud [idSolicitud=" + idSolicitud +", numCifra=" + numCifra +", usuarioBD=" + usuarioBD +"]";

}

and what I want is to concatenate with StringBuilder, they say it's better practice, but how is it done? thanks.

    
asked by Root93 12.07.2018 в 20:04
source

1 answer

5

That concatenation with StringBuilder would be as follows:

import java.lang.StringBuilder;

public class Program {
    public static void main(String[] args) {

        int idSolicitud = 300;
        double numCifra = 3.14;
        char usuarioBD = 'A';

        // Creas un nuevo StringBuilder.
        StringBuilder builder = new StringBuilder();

        // Agregas los String o Variables al builder con append
        builder.append("Solicitud [idSolicitud="); //String
        builder.append(idSolicitud); // Var
        builder.append(", numCifra=");
        builder.append(numCifra);
        builder.append(", usuarioBD=");
        builder.append(usuarioBD);
        builder.append("]");

        // Conviertes a string
        String result = builder.toString();

        // Print result.
        System.out.println(result);
    }
}

Some useful methods:

append() is used to add different objects to your Builder, always at the end, as a queue.

insert() is used to add an object or substring at the specified position.

// Inserta un substring en la posición 2.
builder.insert(2, "xyz");

indexOf() is used to try to find the position of the item you are sending. Returns -1 if it does not exist.

// Intenta encontrar la posición del substring.
int result = builder.indexOf("bc");

delete() is used to delete the Builder content between two positions.

// Borra los characteres desde el index 2 hasta el index 5.
builder.delete(2, 5);

toString() generates your Builder string, whichever it contains.

String result = builder.toString();

substring() generates the string from a position and the desired length (optional parameter)

// Toma un substring despues de los 2 primeros characteres.
String omitFirstTwo = builder.substring(2);
System.out.println(omitFirstTwo);

// Toma solo los 2 primeros characteres. 
String firstTwo = builder.substring(0, 2); // 0 posición - 2 longitud
System.out.println(firstTwo);
  

You can find more information at official documentation

    
answered by 12.07.2018 / 20:21
source