Re: create a string of <n> equal chars <c>
In article <slrni3ovuf.sno.avl@gamma.logic.tuwien.ac.at>,
Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> wrote:
It seems so basic that I can't believe such a feature wasn't in
the standard library:
- given two parameters (int n, char c), return a String that
consists of <n> copies of <c>
(would be imho best suited as a constructor of String itself)
or (what I'd actually need it for:)
- given a String, an int n and a char c, cut or pad(with c) the String
to length n. (the cut/padded one would be a new String, of course)
(I'd need it right-padded, but the problem is the same for left-
padding)
As I know that the strings I need it for are of limited length, and
only a few pad-chars are ever needed, I can help myself, by using
a String constant, like "............................" for each pad-
char, and use an appropriate .substring on it. This sure looks like
a crude hack, but the alternatives involving StringBuffer(*) and
char[n] don't seem much better.
*: StringBuffer.setLength only pads with \u0000, and there doesn't
seem to be an append(numCopies,padChar), either, so one seems
to be bound to adding the same char repeatedly in a loop.
Did I miss some simple idiom? I really hope so.
Homework?
It's easy when the pad character is a constant:
static String padToDigits (final String s, final int digits)
{
final int len= s.length();
if (len > digits)
throw new IllegalArgumentException ("Input too long:" + s);
if (digits > 40)
throw new IllegalArgumentException ("Too many digits:" + digits);
if (len == digits)
return s;
return "0000000000000000000000000000000000000000"
.substring(0, digits - len) + s;
}
When it's not, a for loop to pad a StringBuidler works fine.
--
I won't see Google Groups replies because I must filter them as spam