public static void main(String[] args) {
String str = "武汉市u洪j。山区 HuaZhos无可奈jhkk何花落去 大幅度,,nojgy College j武j昌jjjjjj分校jj。jkl";
URLEncoder.encode(addressChinese,"utf8"); //汉字编码
int byteLength = length(str);
char[] c = str.toCharArray();
int charslength = getCharsLength(c, 12);
System.out.println("getcharlength:" + charslength + "|charat" + str.charAt(charslength - 1));
int sublength = 50;
int subbegin = byteLength - sublength;
System.out.println("source:" + str + "|byteLength:" + byteLength + "|lenth:" + str.length() + "|subbegin:" + subbegin + "|sublength:" + sublength);
String substr2 = substring(str, subbegin, sublength);
System.out.println("------" + substr2 + "--------" + length(substr2));
}
public static String trims(String s) {
if (s == null) {
return "";
} else {
String t = s.replaceAll("^([\\s ])+|([\\s ])+$", "");
return t;
}
}
public static Boolean isBlank(String s) {
if (s == null || trims(s).equals("")) {
return true;
} else {
return false;
}
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]+");
return pattern.matcher(str).matches();
}
public static int length(String s) {
if (str != null) {
return str.getBytes().length;
}
return 0;
}
public static String substring(String str, int srcPos, int specialCharsLength) {
if (str == null || "".equals(str) || specialCharsLength < 1) {
return "";
}
if (srcPos < 0) {
srcPos = 0;
}
if (specialCharsLength <= 0) {
return "";
}
char[] chars = str.toCharArray();
if (srcPos > chars.length) {
return "";
}
int begin = getCharsLength(chars, srcPos);//todo:add
str = str.substring(begin);
chars = str.toCharArray();
int charsLength = getCharsLength(chars, specialCharsLength);
return new String(chars, 0, charsLength);
}
private static int getCharsLength(char[] chars, int specialCharsLength) {
int count = 0;
int normalCharsLength = 0;
for (int i = 0; i < chars.length; i++) {
int specialCharLength = getSpecialCharLength(chars[i]);
if (count <= specialCharsLength - specialCharLength) {
count += specialCharLength;
normalCharsLength++;
} else {
break;
}
}
return normalCharsLength;
}
private static int getSpecialCharLength(char c) {
if (isLetter(c)) {
return 1;
} else {
return 2;
}
}
public static boolean isLetter(char c) {
int k = 0x80;
return c / k == 0 ? true : false;
}
//unicode编码解码
String t= UnicodeUtil.toUnicode("我",true);
String s= new UnicodeUtil().fromUnicode("\\u6211".toCharArray(),0,"\\u6211".length()-1,"".toCharArray()) ;
public static String formatUrl(String url){
if(url!=null){
return url.replaceAll("\"","%22").replaceAll("\\{","%7B").replaceAll("}","%7D").replaceAll("\\[","%5B").replaceAll("]","%5D");
}
return "";
}
|