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:
public static void main(String[] args) {
println new StringBuilder("EUTQQGOPED").insert(6, '-').insert(3, '-');
}
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)
Could use regex, it's slightly clearer what you're doing, but prob not as efficient.
String formattedPin = pin.replaceAll("(.{3})(.{3})(.{4})", "$1-$2-$3")
System.out.println(formattedPin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With