Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner for variable space indentation

In a "pretty print" function for a nested map, I need a simple indent function to prepend the needed space to my structure. I wanted a simple one-liner and the best I found was a 2 line solution. Ideally, I wanted this:

String indentSpace = new String(Arrays.fill(new char[indent], 0, indent-1, ' '));

That doesn't work because Arrays.fill is not 'fluent'; it returns void.

A literal translation of that expression is too verbose for my liking:

char[] chars = new char[indent];
Arrays.fill(chars , ' ');
String indentSpace = new String(chars);

Finally, I settled for a lack-lustre 2-line solution:

private final String indentSpace="                                                     ";
...
String alternative = indentSpace.substring(0,indent % indentSpace.length());

This is minor nit-picking, but I remained curious on whether there's a more elegant solution. I recon that the last option might be a good choice performance-wise.

Any takes?

like image 836
maasg Avatar asked Dec 07 '22 20:12

maasg


1 Answers

The following one-liner should work:

String indentSpace  = new String(new char[indent]).replace('\0', ' ');
like image 175
dogbane Avatar answered Dec 10 '22 11:12

dogbane