编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4
- public class StringSplit {
- public static void main(String[] args) throws Exception {
- String ss = "a很bc你好";
- System.out.println(splitString(ss, 1));
- }
-
- public static String splitString(String str, int byteLength)
- throws Exception {
-
- if(str == null || "".equals(str)) {
- return str;
- }
-
- int wordCount = 0;
-
- byte[] strBytes = str.getBytes("GBK");
-
-
- if (byteLength == 1) {
- if (strBytes[0] < 0) {
- return str.substring(0, 1);
- }
- }
-
- for (int i = 0; i < byteLength; i++) {
- int val = strBytes[i];
- if (val < 0) {
- wordCount++;
- }
- }
-
-
- if (wordCount % 2 == 0) {
- return str.substring(0, (byteLength - (wordCount / 2)));
- }
-
- return str.substring(0, (byteLength - (wordCount / 2) - 1));
-
- }
- }