在java中没有专门的按字节截取字符串,当遇到汉字与字母或数字混合时,就需要自己编写一个函数,如下:
- /**
- * 按字节截取字符串.
- * @param str 要截取的字符串
- * @param beginIndex 按字节取得开始位置
- * @param endIndex 按字节取得结束位置
- * @return 截取的字符串
- * @throws Exception Exception
- */
- public static String bSubstring(final String str, final int beginIndex,
- final int endIndex)
- throws Exception {
- if (str == null || beginIndex >= endIndex) {
- return "";
- }
- char[] chars = str.toCharArray();
- char[] result = new char[endIndex - beginIndex];
- int j = 0;
- for (int i = 0, n = 0; i < chars.length && n < endIndex; ++i) {
- byte[] bytes = String.valueOf(chars[i]).getBytes();
- if (n >= beginIndex) {
- result[j] = chars[i];
- ++j;
- }
- n += bytes.length;
- }
- return String.valueOf(result).substring(0, j);
- }
- /**
- * 按字节截取字符串.
- * @param str 要截取的字符串
- * @param beginIndex 按字节取得开始位置
- * @return 截取的字符串
- * @throws Exception Exception
- */
- public static String bSubstring(final String str, final int beginIndex)
- throws Exception {
- return bSubstring(str, beginIndex, str.getBytes().length);
- }