Java Codespa
/** 截取2個字符中間的字符串 */ private void GetMiddleString() { String str = "BB022220011BB007EBB022220011001100113327EBB000897EBB347E";// 要截取的字符串 String temp; int startIndex = -1, endIndex = -1; do { startIndex = str.indexOf("BB022220011"); // 開始截取的字符位置 endIndex = str.indexOf("7E"); // 最後截取的字符位置 System.out.println("開始截取位置:" + startIndex + ",結束截取位置:" + (endIndex + 2)); if (startIndex < 0) break; temp = str.substring(startIndex, endIndex + 2);// 截出來的字符串 System.out.println("截出來的字符串:" + temp); str = str.substring(temp.length(), str.length());// 剩餘字符串 System.out.println("剩餘字符串:" + str); } while (str.length() > 0); }
輸出結果code
開始截取位置:0,結束截取位置:17
截出來的字符串:BB022220011BB007E
剩餘字符串:BB022220011001100113327EBB000897EBB347E
開始截取位置:0,結束截取位置:24
截出來的字符串:BB022220011001100113327E
剩餘字符串:BB000897EBB347E
開始截取位置:-1,結束截取位置:9