因为'?'并不代表半个汉字,它就是一个问号字符
以下是我的思路代码
- import java.io.UnsupportedEncodingException;
- /*
- * 以字符为单位截取,不会出现半边汉字
- * 当截取的字符所构成的字符串的字节>=所要截取的长度时,停止截取
- */
- public class Test {
- private static String res(String s, int n)
- throws UnsupportedEncodingException {
- StringBuilder bud = new StringBuilder();
- for (int i = 0, le = s.length(); i < le; i++) {
- if (bud.toString().getBytes("GBK").length >= n) {
- return bud.toString();
- }
- bud.append(s.charAt(i));
- }
- return bud.toString();
- }
- public static void main(String[] args) throws UnsupportedEncodingException {
- String s = "abcde物联网fgh";
- for (int i = 0; i < s.length(); i++) {
- System.out.printf("截取%d个字节,实际截取的字符串为::::%s\n", i, res(s, i));
- }
- }
- }
复制代码 |