String Separator in Java

4

I am generating a Jtable that has some information, however there is a field that obtains several data and they are stored to the side inside the same cell, currently separated by a comma (,) but my problem is that I need no last comma.

For example, it looks like this:

  

Juan, Pedro, Pablo,

This is how one words:

String a1 = ResultSet.getString("analisis");
c += a1 + "," ;
    
asked by Juan Pablo 22.10.2018 в 20:08
source

3 answers

5

When you finish concatenating you can use this:

c = c.replaceAll(",$", "");
    
answered by 22.10.2018 / 20:12
source
5

In case you are using Java in version 8 you can use the static method join(CharSequence delimiter, CharSequence... elements) of the class String in the following way:

String a1 = ResultSet.getString("analisis");
String textoFinal = String.join(", ", a1, "Pedro", "Pablo");
System.out.println(textoFinal);
// Si a1 = "Juan" esto imprime:
// Juan, Pedro, Pablo

The first parameter that this method receives is the delimiter character and then all the chains that you want to concatenate.

To learn more about the method you can check its documentation here:

link

And you may find it useful to review this publication:

link

    
answered by 22.10.2018 в 21:03
0

You can use this:

textoFinal = textoFinal.substring(0, textoFinal.lastIndexOf(","));

or

textoFinal = textoFinal.substring(0, textoFinal.length()-1);
    
answered by 24.10.2018 в 14:34