黑马程序员技术交流社区

标题: 【上海校区】Java如何判定字符串中的中文 [打印本页]

作者: 梦缠绕的时候    时间: 2019-2-15 11:26
标题: 【上海校区】Java如何判定字符串中的中文
Java如何判定字符串中的中文
public static String splitString(String str, int len) {
return splitString(str, len, "...");
}
public static String splitString(String str,int len,String elide) {
if (str == null) {
return "";
}
byte[] strByte = str.getBytes();
int strLen = strByte.length;
if (len >= strLen || len < 1) {
return str;
}
int count = 0;
for (int i = 0; i < len; i++) {
int value = (int) strByte;
if (value < 0) {
count++;
}
}
if (count % 2 != 0) {
len = (len == 1) ? len + 1 : len - 1;
}
return new String(strByte, 0, len) + elide.trim();
}
方法一:
public static int countChineseCharacter(String originStr) {
int count = 0;
String temp = null;
for (int i = 0; i < originStr.length(); i++) {
temp = String.valueOf(originStr.charAt(i));
if (temp.getBytes().length == 2)
count++;
}
return count;
}

方法二:
public static int countChinese(String originalStr){
int count = 0;
Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
Matcher matcher = pattern.matcher(originalStr);
while(matcher.find())
count++;
return count;
}


作者: 不二晨    时间: 2019-2-20 09:28
今天也要加油鸭




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2