Is there some easy way to pad Strings in Java.
seems like something that should be in some stringUtil like api but i cant find any.
Is there some easy way to pad Strings in Java.
seems like something that should be in some stringUtil like api but i cant find any.
Apache StringUtils has several methods: leftPad, rightPad, center and repeat. http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringUtils.html
[EDIT]
As others have mentioned, String.format() and the Formatter classes in the JDK are better options. Use them over the commons code.
Besides Apache Commons, also see String.format
which should be able to take care of simple padding (e.g. with spaces).
Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)
.
But the algorithm is very simple (pad right up to size chars):
public String pad(String str, int size, char padChar)
{
StringBuffer padded = new StringBuffer(str);
while (padded.length() < size)
{
padded.append(padChar);
}
return padded.toString();
}
You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:
public class RightPadder {
private int length;
private String padding;
public RightPadder(int length, String pad) {
this.length = length;
StringBuilder sb = new StringBuilder(pad);
while (sb.length() < length) {
sb.append(sb);
}
padding = sb.toString();
}
public String pad(String s) {
return (s.length() < length ? s + padding : s).substring(0, length);
}
}
As an alternative, you can make the result length a parameter to the pad(...)
method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.
(Hint: For extra credit, make it thread-safe! ;-)
java.util.Formatter
will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).
[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]
Since 1.5, String.format() can be used to left/right pad a given string.
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$#" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 25) + "*");
}
/*
output :
Howto *
Howto*
*/
On the issue of the apache function vs the string formatter there is little doubt that the apache function is more clear and easy to read.
Wrapping the formatter in function names isn't ideal.
Hi, you can use the built in StringBuilder append() and insert() methods, for padding of variable string lengths:
AbstractStringBuilder append(CharSequence s, int start, int end) ;
For Example:
private static final String MAX_STRING = " "; //20 spaces
Set<StringBuilder> set= new HashSet<StringBuilder>();
set.add(new StringBuilder("12345678"));
set.add(new StringBuilder("123456789"));
set.add(new StringBuilder("1234567811"));
set.add(new StringBuilder("12345678123"));
set.add(new StringBuilder("1234567812234"));
set.add(new StringBuilder("1234567812222"));
set.add(new StringBuilder("12345678122334"));
for(StringBuilder padMe: set)
padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());
i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.
public static String pad(String str, int size, char padChar)
{
if (str.length() < size)
{
char[] temp = new char[size];
int i = 0;
while (i < str.length())
{
temp[i] = str.charAt(i);
i++;
}
while (i < size)
{
temp[i] = padChar;
i++;
}
str = new String(temp);
}
return str;
}
the formatter solution is not optimal. just building the format string creates 2 new strings.
apache's solution can be improved by initializing the sb with the target size so replacing below
StringBuffer padded = new StringBuffer(str);
with
StringBuffer padded = new StringBuffer(pad);
padded.append(value);
would prevent the sb's internal buffer from growing.
This took me a little while to figure out. The real key is to read that Formatter documentation.
// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
// See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
// Format: %[argument_index$][flags][width]conversion
// Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
"%1$32x",
digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);