package rebelsky.util;

/**
 * A collection of simple string utilities.  Mostly intended to simplify
 * the formatting of output.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of February 1998
 */
public class StringUtils
{
  // +-----------+---------------------------------------------------------
  // | Variables |
  // +-----------+

  /**
   * A collection of spaces.
   */
  public static String spaces = " ";


  // +----------------+----------------------------------------------------
  // | Static Methods |
  // +----------------+

  /**
   * Create a string of the given width with the given string centered
   * and surrounded by spaces.
   * <br>pre: width >= str.length()
   * <br>post: an appropriate string is returned
   *
   * @return a string with a centered version of the original string.
   */
  public static String center(String str, int width) 
  {
    // The number of spaces before the string in the centered version.
    int pre = (width - str.length()) / 2;
    // The number of spaces after the string in the centered version.
    int post = (width - str.length() - pre);
    // Go!
    return spaces(pre) + str + spaces(post);
  } // center(String,int)

  /**
   * Create a string of the given width with the given string 
   * left justified (followed by an appropriate number of spaces).
   * <br>pre: width >= str.length()
   * <br>post: an appropriate string is returned
   *
   * @return a string with a centered version of the original string.
   */
  public static String left(String str, int width) 
  {
    return str + spaces(width-str.length());
  } // left(String,int)

  /**
   * Create a string of the given width with the given string 
   * right justified (preceded by an appropriate number of spaces).
   * <br>pre: width >= str.length()
   * <br>post: an appropriate string is returned
   *
   * @return a string with a centered version of the original string.
   */
  public static String right(String str, int width) 
  {
    return spaces(width-str.length()) + str;
  } // right(String,int)

  /**
   * Get a certain number of spaces.
   */
  public static String spaces(int width)
  {
    // Make sure we have enough in our String
    while (spaces.length() < width) {
      spaces = spaces + spaces;
    }
    // Return the appropriate portion
    return spaces.substring(0,width);
  } // spaces

  // +----------------------+----------------------------------------------
  // | Local Static Methods |
  // +----------------------+

} // StringUtils


