最代码官方
2016-09-19 11:29:31
原证
java字符串截取substring的自定义需求代码片段实现:中文1,英文占0.5的算法实现
今天有个需求要实现字符串截取,但是产品需求比较特殊,中文算1个长度,英文,数字等算0.5个,比如:
中1中2中3
截取2个的话是
中1
截取3个的话是
中1中
以此类推。
分享下代码片段:
public static boolean isChinese(String str) {
String regEx = "[\u4e00-\u9fa5]";
Pattern pat = Pattern.compile(regEx);
Matcher matcher = pat.matcher(str);
boolean flg = false;
if (matcher.find())
flg = true;
return flg;
}
public static String complexSubstring(String value, double len) {
String ret = "";
String[] _arr = value.split("");
// 第一个字符是无效的,去掉即可
_arr[0] = null;
double size = 0;
for (String s : _arr) {
if (s == null) {
continue;
}
if (isChinese(s)) {
size += 1;
} else {
size += 0.5;
}
ret += s;
if (size >= len) {
break;
}
}
return ret;
}
public static void main(String[] args) {
String string = "中1中2中3";
System.out.println(complexSubstring(string, 2));
System.out.println(complexSubstring(string, 3));
System.out.println(complexSubstring(string, 5));
}
执行效果如下图
猜你喜欢
请下载代码后再发表评论
相关代码
最近下载
最近浏览
微信网友_6411724627349504 LV3
2023年4月3日
浪里格朗 LV4
2023年1月31日
heqian LV17
2023年1月10日
Zeorwyc LV8
2022年5月7日
2131234t3 LV1
2021年8月1日
123hdhdhd LV10
2019年12月1日
猿来就是你 LV12
2019年11月21日
幻羽揚 LV4
2019年11月18日
cq92104 LV11
2019年11月5日
xiaoshuai0305 LV1
2019年9月29日





