Java String substring from left

Description

Java String substring from left

public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com";
    int len = 2;//ww w.j  a  v  a2 s.c o m
    System.out.println(left(str, len));
  }
  public static final String EMPTY = "";

  /**
   * <p>
   * Gets the leftmost <code>len</code> characters of a String.
   * </p>
   *
   * <p>
   * If <code>len</code> characters are not available, or the String is
   * <code>null</code>, the String will be returned without an exception. An
   * exception is thrown if len is negative.
   * </p>
   *
   * <pre>
   * left(null, *)    = null
   * left(*, -ve)     = ""
   * left("", *)      = ""
   * left("abc", 0)   = ""
   * left("abc", 2)   = "ab"
   * left("abc", 4)   = "abc"
   * </pre>
   *
   * @param str
   *          the String to get the leftmost characters from, may be null
   * @param len
   *          the length of the required String, must be zero or positive
   * @return the leftmost characters, <code>null</code> if null String input
   */
  public static String left(String str, int len) {
    if (str == null) {
      return null;
    }
    if (len < 0) {
      return EMPTY;
    }
    if (str.length() <= len) {
      return str;
    }
    return str.substring(0, len);
  }
}



PreviousNext

Related