远方蔚蓝
一刹那情真,相逢不如不见

文章数量 126

访问次数 199827

运行天数 1437

最近活跃 2024-10-04 23:36:48

进入后台管理系统

substring按照两个字节来进行截取字符串


正常截取一段字符串,substring按照单个字节来进行截取,如果碰到包含汉字在内的字符串截取,就会截取不准确
比如:123汉字5678,按字符串长度长度为5,按getByte("GBK")则长度为7,此时substring(6, 7)想截取到6,截取就会不准确
private static String subStringByByte(String str, int beginIndex, int endIndex) {  
	    if (beginIndex < 0) throw new StringIndexOutOfBoundsException(beginIndex);  
	    if (beginIndex > endIndex) throw new StringIndexOutOfBoundsException(endIndex - beginIndex);  
	    if (beginIndex == endIndex) return "";  
	    int byteLength = 0;  
	    String returnString = "";  
	    for (int i = 0; byteLength < endIndex && i < str.length(); i++) {  
	        char c = str.charAt(i);  
	        byteLength += (31 < c && c < 128) ? 1 : 2;  
	        if (byteLength > beginIndex)  
	            returnString += c;  
	    }  
	  
	    return returnString;  
	}