Left and right padding a string
In this chapter you will learn:
Right padding
public class Main {
public static void main(String[] argv) {
System.out.println("|" + padRight("asdf", 10) + "|");
}//from j av a 2 s . co m
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
}
The code above generates the following result.
Left padding
public class Main {
public static void main(String[] argv) {
System.out.println("|" + padLeft("java2s.com", 20) + "|");
}//j a v a2s.com
public static String padLeft(String s, int n) {
return String.format("%1$#" + n + "s", s);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » String