截取适合数据库长度的字符串

import java.nio.charset.StandardCharsets;

public class Tools {
    public static void main(String[] args) {
        System.out.println(splitString("[计算费用应judnsdjwddqwhwqdwdqhwdqhwqhqwihq就得花洒uhuqwduhqwudquwhuqdwuhdqwqdw请重新计算;", 128));
    }
      /**
       * 字符串按字节截取 
       * @param str 原字符 
       * @param len 截取长度 
       * @return String
       * @author kinglong 
       * @since 2006.07.20 
       */  
       public static String splitString(String str,int len) {
              if (str == null) {
                     return "";  
              }  
              byte[] strByte = str.getBytes();  
              int strLen = strByte.length;  
              if (len >= strLen) {
                     return str;  
              }
              if(str.length() >= len){
                  str = str.substring(0, len);
              }
              String str1 = "";
              for(int i = str.length(); 1 > 0; i--){
                  str1 = str.substring(0, i);
                  if(str1.getBytes(StandardCharsets.UTF_8).length <= len){
                      break;
                  }
              }


             return str1;
       }  
} 

 

posted @ 2024-03-25 11:52  愚蠢的程序员  阅读(1)  评论(0编辑  收藏  举报