Is there a more subtle / elegant way to format the next social security number, such as String with or without Groovy?

BEFORE:

EUTQQGOPED

AFTER:

EUT-QQG-OPED

The example below is what I came up with to add '-' to a string with 10 characters as part of the readability requirement. The formatting pattern is similar to how often the US Social Security format is used.

Is there a simpler, less verbose way to execute an 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
}
+5
source share
5 answers

I think what you did is the best way to do this, however you could make it more elegant by simply enclosing everything as shown below:

public static void main(String[] args) {
    println new StringBuilder("EUTQQGOPED").insert(6, '-').insert(3, '-');
}

- , StringBuilder ( ).

, , , , . , .

... "less code == good" ( , , IMHO )

+7

regex, , , .

String formattedPin = pin.replaceAll("(.{3})(.{3})(.{4})", "$1-$2-$3")
System.out.println(formattedPin);
+5

These are a few of the options Groovy gives you. In this case, they are not necessarily read very easily, but they are pleasant and short.

    def pin = "EUTQQGOPED"

    // Option 1
    def formatted1 = "${pin[0..2]}-${pin[3..5]}-${pin[6..-1]}" 
    println formatted1

    // Option 2
    def pt1 = pin[0..2]
    def pt2 = pin[3..5]
    def pt3 = pin[6..-1]

    def formatted2 = pt1 << "-" << pt2 << "-" << pt3
    println formatted2
+2
source

While I like the String.format option , I think its breakdown looks more ugly.

    String pin = "EUTQQGOPED";
    System.out.println(String.format("%s-%s-%s", pin.substring(0, 3), pin.substring(3,6), pin.substring(6)));
+2
source

For simplicity, I would go with:

def pin = "EUTQQGOPED"
def formatted = [pin[0..2], pin[3..5], pin[6..-1]].join('-')

For brevity, this can be a hack, but it is very short (and I think it is readable enough):

def formatted = "-$pin"[1..3, 0, 4..6, 0, 7..10]
+2
source

All Articles