您的位置:首页 > 编程语言 > Java开发

【Java笔试题】按字节截取字符串

2016-11-29 13:32 246 查看
1、题目

定义一个方法,按照最大的字节数来截取子串。例如,对“ab你好”,如果取三个字节,那么子串就是ab与“你”字的一半,另一半就要舍弃;如果取四个字节,那么子串就是“ab你”,取五个字节,还是“ab你”。

2、Java代码

import java.io.IOException;
public class CutString {
public static void main(String[] args) throws IOException {
String str = "hit5211314";
int len = str.getBytes("utf-8").length;
for (int x = 0; x < len; x++) {
System.out.println("截取" + (x + 1) + "个字符 : " + cutStringByU8Byte(str, x + 1));
}
}

public static String cutStringByU8Byte(String str, int len) throws IOException {  //用utf-8格式截取
byte[] buf = str.getBytes("utf-8");
int count = 0;
for (int x = len - 1; x >= 0; x--) {
if (buf[x] < 0)
count++;
else
break;
}
if (count % 3 == 0)
return new String(buf, 0, len, "utf-8");
else if (count % 3 == 1)
return new String(buf, 0, len - 1, "utf-8");
else
return new String(buf, 0, len - 2, "utf-8");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: