I am using Formatter to output Java code to a file. I want to add a specific number of spaces to the start of each line. My problem is I cannot find a way to do this "neatly". The standard options seem to only allow adding a minimum number of spaces but not a specific number of spaces.

As a work around, I am currently doing the following: out.format("%7s%s", "", "My text"); but I'd like to do it with only two arguments like this out.format("%7s", "My text");.

Does anyone know if there is a way to do this using the standard Formatter options?

有帮助吗?

解决方案

I'm not exactly sure what you want here:

out.format("xxx%10sxxx", "My text");
// prints: xxx   My textxxx

While:

out.format("xxx%-10sxxx", "My text");
// prints: xxxMy text   xxx

As far as I know, there is no way to do the old C-style formatting to specify the size in an argument like "%*s" because then you could pass in (str.length() + 7).

I'm afraid that your way seems to the the most "neat". If you can explain why you don't like it maybe we can find a better workaround.

其他提示

You can prepend text into your string. Another way to reapet any string which you can use this code:-

String str = "abc";
String repeated = StringUtils.repeat(str, 3);

here StringUtils is org.apache.commons.lang3.StringUtils class.

Use Commons Lang

String line = "Hello World!";
int numberOfSpaces = 2;
String lineWithSpacePadding = StringUtils.leftPad(line, line.length() + numberOfSpaces);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top