Get substring and handle null - Android java.lang

Android examples for java.lang:String Substring

Description

Get substring and handle null

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{

    /**//w w  w.jav a 2  s . c  om
     * <pre>
     * StringUtil.substring(null, *)    = null
     * StringUtil.substring("", *)      = ""
     * StringUtil.substring("han", 1)   = "an"
     * StringUtil.substring("han", 615) = ""
     * StringUtil.substring("han", -1)  = ""
     * </pre>
     * 
     * @param str
     * @param beginIndex
     *            ?? ???????(0?? ??)
     * @return
     */
    public static String substring(String str, int beginIndex) {
        if (str == null) {
            return null;
        }

        if (beginIndex < 0) {
            return "";
        }

        if (beginIndex > str.length()) {
            return "";
        }

        return str.substring(beginIndex);
    }
    /**
     * <pre>
     * StringUtil.substring(null, *, *)    = null
     * StringUtil.substring("", *, *)      = ""
     * StringUtil.substring("han", 1, 2)   = "a"
     * StringUtil.substring("han", 1, 3)   = "an"
     * StringUtil.substring("han", 1, 615) = "an"
     * StringUtil.substring("han", -1, *)  = ""
     * StringUtil.substring("han", *, -1)  = ""
     * </pre>
     * 
     * @param str
     * @param beginIndex
     * @param endIndex
     * @return
     */
    public static String substring(String str, int beginIndex, int endIndex) {
        if (str == null) {
            return null;
        }

        if (beginIndex < 0 || endIndex < 0) {
            return "";
        }

        if (endIndex > str.length()) {
            endIndex = str.length();
        }

        if (beginIndex > endIndex || beginIndex > str.length()) {
            return "";
        }

        return str.substring(beginIndex, endIndex);
    }

}

Related Tutorials