开发者

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 litera开发者_高级运维l 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?


The following one-liner should work:

String indentSpace  = new String(new char[indent]).replace('\0', ' ');


If indeed line count is your primary measurement then this is a compact way to create a String with n spaces:

String spaces = n == 0 ? "" : String.format("%" + n + "s", "");

Performance is probably not so great.


If you need to create a string with just spaces in it then StringUtils.repeat will work:

String indentSpace = StringUtils.repeat(' ', indent);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜