Java examples for java.lang:String Pad
Right-pad a String with a configurable padding character.
/*/*from ww w .ja v a 2 s. c o m*/ * Copyright 2009-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String string = "java2s.com"; int size = 2; System.out.println(padRight(string, size)); } /** * Right-pad a String with a configurable padding character. * * @param string The String to pad * @param size Pad String by the number of characters. * @param paddingChar The character to pad the String with. * @return The padded String. If the provided String is null, an empty String is returned. */ public static String padRight(String string, int size, char paddingChar) { if (string == null) { return ""; } StringBuilder padded = new StringBuilder(string); while (padded.length() < size) { padded.append(paddingChar); } return padded.toString(); } /** * Right-pad the provided String with empty spaces. * * @param string The String to pad * @param size Pad String by the number of characters. * @return The padded String. If the provided String is null, an empty String is returned. */ public static String padRight(String string, int size) { return padRight(string, size, ' '); } }