1. 程式人生 > >java擷取2個指定字元之間的字串

java擷取2個指定字元之間的字串

擷取2個指定字元之間的字串:
/**
     * 擷取字串str中指定字元 strStart、strEnd之間的字串
     * 
     * @param string
     * @param str1
     * @param str2
     * @return
     */
    public static String subString(String str, String strStart, String strEnd) {

        /* 找出指定的2個字元在 該字串裡面的 位置 */
        int strStartIndex = str.indexOf(strStart);
        int strEndIndex = str.indexOf(strEnd);

        /* index 為負數 即表示該字串中 沒有該字元 */
        if (strStartIndex < 0) {
            return "字串 :---->" + str + "<---- 中不存在 " + strStart + ", 無法擷取目標字串";
        }
        if (strEndIndex < 0) {
            return "字串 :---->" + str + "<---- 中不存在 " + strEnd + ", 無法擷取目標字串";
        }
        /* 開始擷取 */
        String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
        return result;
    }



簡單粗暴的方式:

-------擷取指定2個字元之間的字串
public String splitData(String str, String strStart, String strEnd) {
        String tempStr;
        tempStr = str.substring(str.indexOf(strStart) + 1, str.lastIndexOf(strEnd));
        return tempStr;
    }