Java examples for java.lang:String Format
align String To Center
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String s = "java2s.com"; int size = 2; System.out.println(alignToCenter(s, size)); }//from ww w . ja va 2 s.co m public static String alignToCenter(String s, int size) { if (s.length() < size - 1) { int halfSize = (size - s.length()) / 2; int remainder = (size - s.length()) % 2; String pattern = "%-" + halfSize + "s%s%" + (halfSize + remainder) + "s"; return String.format(pattern, "|", s, "|").replace(" ", "-"); } return String.format("%-" + size + "s", s).replace(" ", "-"); } }