- public class CutString {
- /**
- * @param input
- * 输入字符串
- * @param subLength
- * 想要截取的字节数
- * @throws UnsupportedEncodingException
- */
-
- public String subStrByBytes(String input, int subLength)
- throws UnsupportedEncodingException {
- // 总的字符数,A是一个字符,汉字也只是一个字符
- int totalCharacter = input.length();
- // 总的字节数
- int totalBytes = input.getBytes("GBK").length;
-
- System.out.println("字符串\"" + input + "\"的总字节数是: " +
- input.getBytes("GBK").length + "\n" + "总字符数是: " +
- totalCharacter);
- if(subLength > totalBytes){
- System.err.println("输入长度错误!请重新输入。");
- return "";
- }
-
- int current = 0;
- String result = "";
-
- // 遍历字符串,直到截取目标长度
- for (int i = 0; i < totalCharacter; i++) {
- String tmp = input.substring(i, i + 1);
- int c_len = tmp.getBytes("GBK").length;
- if (current < subLength) {
- current += c_len;
- result += tmp;
- }
- }
- System.out.println("截取" + subLength + "个字节后的结果是: " + result + "\n");
- return result;
- }
- public static void main(String[] args) throws UnsupportedEncodingException {
- String str1 = "我ABC";
- int len1 = 4;
- String str2 = "我ABC汉DEF";
- int len2 = 6;
-
- Test10 demo1 = new Test10();
- //打印字符串我"我ABC"截取4个字节的结果
- String out1 = demo1.subStrByBytes(str1, len1);
-
- Test10 demo2 = new Test10();
- //打印字符串我"我ABC汉DEF"截取6个字节的结果
- String out2 = demo2.subStrByBytes(str2, len2);
-
- }
- }
复制代码 |