I Spy Code - Java

Center a string

Question:

Write a java program that centers a string.

Solution:

Here is a java example that center justifies a string :

Source: (Example.java)

import org.apache.commons.lang.StringUtils;
 
public class Example {
 
   public static void main(String[] args) {
 
      System.out.println("12345678901234567890");
      System.out.println("--------------------");
 
      String str2 = StringUtils.center("hello", 20);
      System.out.println(str2);
 
      String str3 = StringUtils.center("this-is-a-word", 20);
      System.out.println(str3);
 
      String str4 = StringUtils.center("bye", 20);
      System.out.println(str4);
 
   }
}
 

Output:

$ java Example
12345678901234567890
--------------------
       hello        
   this-is-a-word   
        bye       

References:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#center-java.lang.String-int-

Questions answered by this page:

Center justify string java example