Reputation: 1942
I'm trying to format a phone number which is stored without formatting in a database. Now currently I just use substring and String concatination to form the formatted String but I'm looking for a cleaner/faster/less memory intensive method. (and I don't mean just using a StringBuilder).
I looked at String.format but that only takes a list of parameters (as in ...) and not a chararray.
Upvotes: 2
Views: 278
Reputation: 1942
I'll toss in my 2 cents after some lookup:
import java.swing.text.MaskFormater;
try {
MaskFormatter formatter = new MaskFormatter("+AA AAA AA AA AA");
formatter.setValueContainsLiteralCharacters(false);
System.err.println(formatter.valueToString("31987365414"));
} catch (ParseException e) {
}
Upvotes: 5
Reputation: 36577
If you want to build a String
from char array(s) plus some things (chars, strings, whatever) between them, then StringBuilder
is definitely the right way to go, if you don't want to simply concatenate. An important point is to initialize the builder with enough initial capacity so that it doesn't need to reallocate its internals while building.
Upvotes: 1