Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more terse/elegant way to format the following Social Security Number like String with or without Groovy?

Tags:

java

groovy

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
}
like image 438
Brian Avatar asked Mar 20 '12 23:03

Brian


2 Answers

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)

like image 124
Bohemian Avatar answered Oct 09 '22 09:10

Bohemian


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);
like image 32
Adam Avatar answered Oct 09 '22 11:10

Adam