Get substring from middle - Android java.lang

Android examples for java.lang:String Substring

Description

Get substring from middle

Demo Code

public class Main {

  /**/*from   w w  w.j  a  v  a  2  s . com*/
   * <pre>
   * StringUtil.mid(null, *, *)    = null
   * StringUtil.mid(*, *, -length) = ""
   * StringUtil.mid("han", 0, 1)   = "h"
   * StringUtil.mid("han", 0, 11)  = "han"
   * StringUtil.mid("han", 2, 3)   = "n"
   * StringUtil.mid("han", -2, 3)  = "han"
   * </pre>
   * 
   * @return
   */
  public static String mid(String str, int beginIndex, int length) {
    if (str == null) {
      return null;
    }
    if (length < 0 || beginIndex > str.length()) {
      return "";
    }
    if (beginIndex < 0) {
      beginIndex = 0;
    }
    if (str.length() <= (beginIndex + length)) {
      return str.substring(beginIndex);
    }
    return str.substring(beginIndex, beginIndex + length);
  }

}

Related Tutorials