Friday 24 January 2020

Java: Pad string with stars


Using ‘String.format’ function you can pad string with specific characters.

Following function right pad the string with given character.
String rightPad(String str, int n, char charToPad) {
         return String.format("%-" + n + "s", str).replace(' ', charToPad);
}

Following function left pad the string with given character.
String leftPad(String str, int n, char charToPad) {
         return String.format("%" + n + "s", str).replace(' ', charToPad);
}

App.java
package com.sample.app;

public class App {

 private static String rightPad(String str, int n, char charToPad) {
  return String.format("%-" + n + "s", str).replace(' ', charToPad);
 }

 private static String leftPad(String str, int n, char charToPad) {
  return String.format("%" + n + "s", str).replace(' ', charToPad);
 }

 public static void main(String[] args) {
  String str = "hello";

  String leftPad = leftPad(str, 10, '*');
  String rightPad = rightPad(str, 10, '*');

  System.out.println(leftPad);
  System.out.println(rightPad);
 }

}

Output
*****hello
hello*****


You may like

No comments:

Post a Comment