阅读350 返回首页    go 阿里云 go 技术社区[云栖]


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

public static void main(String[] args) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		// 原始字符串
		String s = "我ZWR爱JAVA";
		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;
	}


 

最后更新:2017-04-02 06:52:08

  上一篇:go isspace &lt;ctype.h&gt; &lt;cctype&gt;
  下一篇:go Thinking in Java,,敏捷软件开发原则、实践与设计模式