Get substring and handle null string value - Android java.lang

Android examples for java.lang:String Substring

Description

Get substring and handle null string value

Demo Code

import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    /**//from w w w. j av a 2 s . c  om

     * <pre>
     * StringUtil.substring(null, *, *) = null
     * StringUtil.substring("", * , *) = "";
     * StringUtil.substring("abc", 0, 2) = "ab"
     * StringUtil.substring("abc", 2, 0) = ""
     * StringUtil.substring("abc", 2, 4) = "c"
     * StringUtil.substring("abc", 4, 6) = ""
     * StringUtil.substring("abc", 2, 2) = ""
     * StringUtil.substring("abc", -2, -1) = "b"
     * StringUtil.substring("abc", -4, 2) = "ab"
     * </pre>
     */
    public static String substring(String str, int start, int end) {
        if (str == null) {
            return null;
        }

        if (end < 0) {
            end = str.length() + end;
        }

        if (start < 0) {
            start = str.length() + start;
        }

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

        if (start > end) {
            return "";
        }

        if (start < 0) {
            start = 0;
        }

        if (end < 0) {
            end = 0;
        }

        return str.substring(start, end);
    }

}

Related Tutorials