Get substring from left - Android java.lang

Android examples for java.lang:String Substring

Description

Get substring from left

Demo Code

import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    /**// ww  w. j  a v  a2s  .c  o m
     * 
     * <pre>
     * StringUtil.left(null, *)    = null
     * StringUtil.left(*, -length) = ""
     * StringUtil.left("", *)      = *
     * StringUtil.left("han", 0)   = ""
     * StringUtil.left("han", 1)   = "h"
     * StringUtil.left("han", 11)  = "han"
     * </pre>
     * 
     */
    public static String left(String str, int length) {
        if (str == null) {
            return null;
        }
        if (length < 0) {
            return "";
        }
        if (str.length() <= length) {
            return str;
        }
        return str.substring(0, length);
    }

}

Related Tutorials