---
title: "按字节长度截取字符串"
author: "teasp"
date: "2014-08-11T17:22:34Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-08-11T17:22:34Z"
id: 2102537
url: "https://teasp.iteye.com/blog/2102537"
---

需求：按字节数截取字符串，但是不允许劈开汉字。

 

public static final String subStrViaByteLen(String src, Charset charset, int len) {  
  if (src==null || src.length()&lt;1) {  
   return src;  
  }  
  if (len &lt; 1) {  
   return "";  
  }  
  byte\[] tmp = src.getBytes(charset);  
  String sub = new String(tmp, 0, len, charset);  
  int lastIndex = sub.length()-1;  
  if (sub.charAt(lastIndex) != src.charAt(lastIndex)) {  
   sub = sub.substring(0, lastIndex);  
  }  
    
  return sub;  
 }