- package com.cg.test5;
- import java.io.IOException;
- public class Test {
- public static void main(String[] args) throws IOException {
- String string="abc你好呀,我真的很想进黑马!Hello";
- int len=string.getBytes("utf-8").length;
- for(int x=0;x<len;x++){
- System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByU8Byte(string,x+1));
- }
- }
-
- public static String cutStringByU8Byte(String str,int len) throws IOException{
- 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");
- }
- }
-
- }
复制代码 |