Thursday, May 20, 2010

On "meta-formatting" experiments

I've been way too obsessed with stackoverflow to write in the blog, but here's a fun little snippet:
String[] arr = { "a", "b", "c" };
final int N = arr.length;
String format = new String(new char[N])
    .replace("\0", ":")
    .replaceAll(".(?=(.)?)", "%s$1");
System.out.println(format);      // prints "%s:%s:%s"
System.out.format(format, arr);  // prints "a:b:c"
Not knowing any better, I call this "meta-formatting", i.e. the programmatic generation of formatting strings. It's really not that much different than "meta-regexing", i.e. the programmatic generation of... do I really have to say this?

And here's a slightly more complicated example:
String[] arr = { "alpha", "omega", "xxx", "yyy" };
final int N = arr.length;
String format = new String(new char[N/2])
    .replaceAll(".", "(%7s : %-7s)%n");
System.out.format(format, arr);
// prints: (  alpha : omega  )
//         (    xxx : yyy    )
And another one for giggles:
String[] arr = { "a", "b", "c", "d" };
final int N = arr.length;
String format = new String(new char[N])
    .replaceAll("(?<=(^.*)).", "%s$1")
    .replaceAll("(?!^)(?=%)", " = ")
    .replaceAll("\0", "+%<s");
System.out.format(format, arr);
// prints "a = b+b = c+c+c = d+d+d+d"

No comments:

Post a Comment