Reputation: 13571
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
}
Upvotes: 5
Views: 3610
Reputation: 19229
For simplicity, I'd go with:
def pin = "EUTQQGOPED"
def formatted = [pin[0..2], pin[3..5], pin[6..-1]].join('-')
For brevity, this might be a hack, but it's very short (and I think it's quite readable too hehe):
def formatted = "-$pin"[1..3, 0, 4..6, 0, 7..10]
Upvotes: 3
Reputation: 425208
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)
Upvotes: 7
Reputation: 1967
Whilst I like the String.format option, I think breaking it up looks uglier.
String pin = "EUTQQGOPED";
System.out.println(String.format("%s-%s-%s", pin.substring(0, 3), pin.substring(3,6), pin.substring(6)));
Upvotes: 2
Reputation: 1970
These are a couple of options that Groovy gives you. They don't necessarily read very easily in this case, but they are nice 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
Upvotes: 2
Reputation: 36723
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);
Upvotes: 5