How can I pad a String in Java?
Apache StringUtils
has several methods: leftPad
, rightPad
, center
and repeat
.
But please note that — as others have mentioned and demonstrated in this answer — String.format()
and the Formatter
classes in the JDK are better options. Use them over the commons code.
Left padding a String with Zeros
If your string contains numbers only, you can make it an integer and then do padding:
String.format("%010d", Integer.parseInt(mystring));
If not I would like to know how it can be done.
Java pad string with specific characters
Other way how you can do it:
String.format("%8s", "helllo").replace(' ', '*');
In this case you do not need to add library.
Java pad string with space
Hope this might help
String email = "abc@jhkj.com";
System.out.println(String.format("Home:%1$3s%s%s", "", email));
Output:Home: abc@jhkj.com
How to pad Strings with Unicode characters in Java
There are actually a few issues here, other than that some fonts display the flag wider than the other characters. I assume that you want to count the Chinese flag as a single character (as it is drawn as a single element on the screen).
The String class reports an incorrect length
The String class works with char
s, which are 16-bit integers of Unicode code points. The problem is that not all code points fit in 16 bits, only code points from the Basic Multilingual Plane (BMP) fit in those char
s. String
's length()
method returns the number of char
s, not the number of code points.
Now String
's codePointCount
method may help in this case: it counts the number of code points in the given index range. So providing string.length()
as second argument to the method returns the total count of code points.
Combining characters
However, there's another problem. The Chinese flag, for example, consists of two Unicode code points: the Regional Indicator Symbol Letters C (, U+1F1E8) and N (, U+1F1F3). Those two code points are combined into a flag of China. This is a problem you are not going to solve with the codePointCount
method.
The Regional Indicator Symbol Letters seem to be a special occasion. Two of those characters can be combined into a national flag. I am not aware of a standard way to achieve what you want. You may have to take that manually into account.
I've written a small program to get the length of a string.
static int length(String str) {
String a = "\uD83C\uDDE6";
String z = "\uD83C\uDDFF";
Pattern p = Pattern.compile("[" + a + "-" + z + "]{2}");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()) {
count++;
}
return str.codePointCount(0, str.length()) - count;
}
How to pad a formatted string
What is it about "msg" that does not let me pad it?
It's longer than 10 characters.
That 10
is the width of the Formatter
class.
Reading that documentation, you'll see
The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.
So, minimum, meaning any string longer than that are printed as-is.
If you want to pad, just add 10 to the length of the string.
String msg = "some really, really long message";
String fmt = "%1$" + (10 + msg.length()) + "s";
String pad = String.format(fmt, msg);
// " some really, really long message"
Java padding a string read from a file
A simple solution:
public static String pad_num(String line){
String[] groups = line.split("-");
String left = groups[0],
right = groups[1];
if(left.length() < right.length()) {
do {
left = '0'+left;
} while (left.length() < right.length());
} else if(right.length() < left.length()) {
do {
right = '0'+right;
} while (right.length() < left.length());
}
return left+'-'+right;
}
If you don't have fixed operator, you can pass it as an argument:
public static String pad_num(String line, String operator){
//prevent ArrayIndexOutOfBoundsException
if(!line.contains(operator)) {
return line;
}
//prevent PatternSyntaxException by compiling it as literal
String[] groups = Pattern.compile(operator, Pattern.LITERAL).split(line);
//do the same
...
return left+operator+right;
}
how to string pad with variables instead of hard coded numbers inside %s in java
You could use "%-"+namePad+"s"
instead of "%-5s"
Although, I am unsure you really need that variable at all. You are using String.format
, but giving no variables to format, so try this instead.
String.format("%d - %-21s", id, name);
Or, as before
int pad = 21;
return String.format("%d - %-"+pad+"s*", id, name);
For example, (with the *
added to show the padding)
static class Person {
int id;
String name;
public Person(int id, String name) {
this.id = id; this.name = name;
}
public String toString() {
return String.format("%d - %-21s*", id, name);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Person[] people = {
new Person(1, "Bill Gates"),
new Person(2, "Trump"),
new Person(3, "Tail"),
new Person(4, "James Bond")
};
for (Person p : people) {
System.out.println(p);
}
}
Output
1 - Bill Gates *
2 - Trump *
3 - Tail *
4 - James Bond *
Related Topics
What Does "Could Not Find or Load Main Class" Mean
Java String to Date Conversion
How to Use Java.Net.Urlconnection to Fire and Handle Http Requests
Difference Between Public, Protected, Package-Private and Private in Java
Swing Gui Listeners Without Awt
How Do Servlets Work? Instantiation, Sessions, Shared Variables and Multithreading
Why Does My Arraylist Contain N Copies of the Last Item Added to the List
Why Do I Need to Override the Equals and Hashcode Methods in Java
How to Append Text to an Existing File in Java
Inconsistent Performance Applying Foregroundactions in a Jeditorpane When Reading Html
Why Doesn't Recyclerview Have Onitemclicklistener()
Android, Getting Resource Id from String
Custom Fonts and Xml Layouts (Android)
How to Upload a File Using Java Httpclient Library Working With PHP