I need to create variable-length strings of dots/periods/full-stops to add to some text content, in a way that is similar to a formatted table-of-contents:
Chapter 1 .................................... 1
Section 1.1 ................................ 1
Subsection 1.1.2 .......................... 12
I know that things like String.format
exist, but that is not suitable for formatting periods this way.
The code is complicated by the need for there to be many threads doing similar work at the same time.
I have written this utility class that caches a 'base' string in a Thread-local, and uses that to supply the required data.
Are there any alternatives, improvements, or other recommendations you have?
public final class DotPadding {
private static final ThreadLocal<String> PAD_BASE = new ThreadLocal<String>() {
@Override
protected String initialValue() {
return "................";
}
};
public static final String getPadding(final int length) {
if (length <= 0) {
return "";
}
String base = PAD_BASE.get();
if (base.length() >= length) {
return base.substring(0, length);
}
while (base.length() < length) {
base = base.concat(base);
}
PAD_BASE.set(base);
return base.substring(0, length);
}
}
As an example usage, this is one of the ways that the above code is used. There are other places too:
String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
+ " "
+ DotPadding.getPadding(width - (2 + description.length() + index.length()))
+ " "
+ index;
System.out.println(line);
DotPadding.getPaddedString(String left, String right)
? Or is that what the last code block is about? \$\endgroup\$3
will return...
and 5 will return.....
\$\endgroup\$description
andindex
in the last code block, shouldn't that be wrapped in a helper method? \$\endgroup\$