leetcode-0

1
2
3
问题: 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 
但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,
输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
大专栏  leetcode-0ode">
实现-java

/**
* 1.len 小于等于0 输出null
* 2.len 大于字符的字节长度, 输出整个字符
*
* param encoding 编码方式
**/
public static String subStr(String str, int length, String encodeing) throws UnsupportedEncodingException {
if (length <= 0) {
return null;
}

int total = 0;
int index = 0;
for (int i = 0; i < str.length(); ) {
String tmp = str.substring(i, ++i);
total += tmp.getBytes(encodeing).length;
index ++;
if (total >= length) {
break;
}
}
//取较小的
index = (index > str.length()) ? str.length() : index;
return str.substring(0, index);
}
}

猜你喜欢

转载自www.cnblogs.com/sanxiandoupi/p/11711082.html