Java examples for java.lang:String Format
Align string to left by length
//package com.java2s; public class Main { public static void main(String[] argv) { String str = "java2s.com"; int size = 42; System.out.println(alignLeft(str, size)); }/*from w w w . ja v a 2 s. c om*/ public static final String EMPTY_STRING = ""; public static String alignLeft(String str, int size) { return alignLeft(str, size, ' '); } public static String alignLeft(String str, int size, char padChar) { if (str == null) { return null; } int pads = size - str.length(); if (pads <= 0) { return str; } return alignLeft(str, size, String.valueOf(padChar)); } public static String alignLeft(String str, int size, String padStr) { if (str == null) { return null; } if ((padStr == null) || (padStr.length() == 0)) { padStr = " "; } int padLen = padStr.length(); int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; } if (pads == padLen) { return str.concat(padStr); } else if (pads < padLen) { return str.concat(padStr.substring(0, pads)); } else { char[] padding = new char[pads]; char[] padChars = padStr.toCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return str.concat(new String(padding)); } } public static String substring(String str, int start) { if (str == null) { return null; } if (start < 0) { start = str.length() + start; } if (start < 0) { start = 0; } if (start > str.length()) { return EMPTY_STRING; } return str.substring(start); } public static String substring(String str, int start, int end) { if (str == null) { return null; } if (end < 0) { end = str.length() + end; } if (start < 0) { start = str.length() + start; } if (end > str.length()) { end = str.length(); } if (start > end) { return EMPTY_STRING; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } }