Java String substring from right

Description

Java String substring from right

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

  public static final String EMPTY = "";

  /**
   * <p>
   * Gets the rightmost <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 an exception. An
   * exception is thrown if len is negative.
   * </p>
   *
   * <pre>
   * right(null, *)    = null
   * right(*, -ve)     = ""
   * right("", *)      = ""
   * right("abc", 0)   = ""
   * right("abc", 2)   = "bc"
   * right("abc", 4)   = "abc"
   * </pre>
   *
   * @param str
   *          the String to get the rightmost characters from, may be null
   * @param len
   *          the length of the required String, must be zero or positive
   * @return the rightmost characters, <code>null</code> if null String input
   */
  public static String right(String str, int len) {
    if (str == null) {
      return null;
    }
    if (len < 0) {
      return EMPTY;
    }
    if (str.length() <= len) {
      return str;
    }
    return str.substring(str.length() - len);
  }
}



PreviousNext

Related