BEFORE:
EUTQQGOPED
AFTER:
EUT-QQG-OPED
The example below is what I came up with to add ‘-‘ to a 10 character String as part of a readability requirement. The formatting pattern is similar to how a U.S Social Security Number is often formatted.
Is there a simpler, less verbose way of accomplishing the additional format?
public static void main(String[] args){
String pin = "EUTQQGOPED";
StringBuilder formattedPIN = new StringBuilder(pin);
formattedPIN = formattedPIN.insert(3, '-').insert(7, '-');
//output is EUT-QQG-OPED
println formattedPIN
}
I think what you’ve done is the best way to do it, however you could make it more elegant by simply in-lining everything, as follows:
This kind of in-lining is possible due to StringBuilder providing a fluent interface (which allows method chaining).
Also note the transposition of the inserts, because the order you had them in means the first insert affects the parameters of the second insert. By ordering them largest-first means they are basically independent of each other.
And there’s always… “less code == good” (as long as it’s still readable, and in this case it is IMHO more readable)