package com.ge.bean.csr;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Demo { /*** 判断是否为中文字符*/ public static boolean is (char mChar) {boolean is = false;String strTemp = String.valueOf(mChar);String strReg = "[\\u4e00-\\u9fa5]";Pattern p = Pattern.compile(strReg);Matcher m = p.matcher(strTemp);if (m.find()) { is = true;}return is; } public static String getString (String strDemo, int nBytes) {
char[] mChars = strDemo.toCharArray();int nDone = 0;for (int nIdx = 0; nDone < nBytes; nIdx ++) { if (is(mChars[nIdx])) {
nDone += 2; } else {
nDone += 1; }}byte[] mResChars = new byte[nDone];byte[] mBytes = strDemo.getBytes();System.arraycopy(mBytes, 0, mResChars, 0, nDone);return new String(mResChars); } public static void main (String[] args) {String str = "我a是中国人";int nBytes = 4;//输出我a是//int nBytes = 5;//输出我a是System.out.println(getString(str, nBytes)); }} |