Created
March 14, 2011 07:07
-
-
Save yongboy/868861 to your computer and use it in GitHub Desktop.
字符串截取(设定中文长度为2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 定义中文字符Unicode编码范围 | |
*/ | |
private static final String CN_PATTERN = "[\\u4e00-\\u9fbb]+"; | |
public static final String subCnString(String str, int targetLen) { | |
if (str == null || str.equals("")) | |
return str; | |
if (targetLen < 1) | |
return ""; | |
if (str.length() <= (targetLen/2)) { | |
return str; | |
} | |
int defaultLen = 0; | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < str.length(); i++) { | |
String s = str.substring(i, i + 1); | |
int charLen = 1; | |
if (s.matches(CN_PATTERN)) { | |
charLen = 2; | |
} | |
if ((defaultLen + charLen) > targetLen) { | |
break; | |
} | |
defaultLen += charLen; | |
sb.append(s); | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment