您的位置:首页 > 其它

按字节截取含有中文汉字的字符串

2011-11-17 13:41 246 查看
public static void main(String[] args) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		// 原始字符串
		String s = "我ZWR爱J***A";
		System.out.println("原始字符串:" + s);
		try {
		System.out.println("截取前1位:" + CutString.substring(s, 1));
		System.out.println("截取前2位:" + CutString.substring(s, 2));
		System.out.println("截取前4位:" + CutString.substring(s, 4));
		System.out.println("截取前6位:" + CutString.substring(s, 6));
		} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
		}
	}


public static String substring(String orignal, int count) throws UnsupportedEncodingException{
		if(!"".equals(orignal) && orignal != null){
			// 将原始字符串转换为GBK编码格式
			orignal = new String(orignal.getBytes(), "GBK");
			if(count > 0 && count < orignal.length()){
				StringBuffer sb = new StringBuffer();
				char c;
				for (int i = 0; i < count; i++) {
					c = orignal.charAt(i);
					sb.append(c);
					if(isChineseChar(c)){
						// 遇到中文汉字,截取字节总数减1
						--count;
					}
				}
				return sb.toString();
			}
		}
		return orignal;
	}




//判断是否是一个中文汉字
	public static boolean isChineseChar(char c) throws UnsupportedEncodingException{
		return String.valueOf(c).getBytes("GBK").length > 1;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐