Java Data Type How to - Print a String in pyramid Form








Question

We would like to know how to print a String in pyramid Form.

Answer

public class Main {
  public static void main(String args[]) {
    String s = "java2s.com";
    int l;//from  w w w .  ja  va 2 s .  c om
    l = s.length();
    for (int i = 0; i < l; i++) {
      int padding = s.length() - i;
      if (padding > 0) {
        System.out.printf("%" + padding + "s", " ");
      }
      for (int j = 0; j < i; j++) {
        System.out.printf("%c ", s.charAt(j));
      }
      System.out.printf("%c\n", s.charAt(i));
    }
  }
}

The code above generates the following result.