0

I have the following Long: 201700112345, and I want to convert it to 2017.001.12345.

I know I could just use a substring:

long l = 201700112345L;
String s = Long.toString(l);
String result = s.substring(0,4)+"."+s.substring(4,7)+"."+s.substring(7);

But can I also accomplish this with a String.format EDIT: ..with a single input for the Object-varargs parameter of the String.format method?

Some things I've tried:

String.format("%4d.%3d.%5d", l);
// Which resulted in:
java.util.MissingFormatArgumentException: Format specifier '%3d'

Which is quite obvious I realize, because I only have one input instead of three..

I know I can backtrack to the same input using %1$, so I then tried:

String.format("%4d.%1$3d.%1$5d", l);
// Which resulted in:
201700112345.201700112345.201700112345

I also tried this, which gave the correct lengths, but not the correct parts:

String.format("%.4s.%1$.3s.%1$.5s", Long.toString(l));
// Which resulted in:
2017.201.20170

I must admit I haven't used String.format all that often, so I'm not too sure if it's even possible to have some kind of substring as format. And if it is possible, I can't figure it out..

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
  • "can I also accomplish this with a String.format": `String.format("%s.%s.%s", s.substring(0, 4), s.substring(4, 7), s.substring(7))`. – Andy Turner Oct 11 '17 at 09:18
  • 2
    maybe something like [this SO question](https://stackoverflow.com/questions/5114762/how-do-format-a-phone-number-as-a-string-in-java) can help you (just use dots instead of dashes..) – Nino Oct 11 '17 at 09:20
  • @AndyTurner Hehe, yeah, I know it's possible like that. ;) Edited my question. – Kevin Cruijssen Oct 11 '17 at 09:20
  • @Nino Hmm, hadn't thought of using `.replaceAll`. That's also an alternative I guess: `Long.toString(l).replaceAll((.{4})(.{3})(.{5})", "$1.$2.$3"));`. Ah well, will just use `substring` I guess. I was just wondering if this can be accomplished with `String.format` at all, or if `String.format` hasn't anything for substrings in its arsenal. – Kevin Cruijssen Oct 11 '17 at 09:24

1 Answers1

1

A more efficient way to do this than using substring is to use a StringBuilder: this has the append(CharSequence,int,int) method, which allows you to avoid unnecessarily creating substrings:

String formatted =
    new StringBuilder(s.length() + 2)
        .append(s, 0, 4)
        .append('.')
        .append(s, 4, 7)
        .append('.')
        .append(s, 7, s.length())
        .toString();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243