好文档就是一把金锄头!
欢迎来到金锄头文库![会员中心]
电子文档交易市场
安卓APP | ios版本
电子文档交易市场
安卓APP | ios版本

java应用-截取字符串.doc

2页
  • 卖家[上传人]:xiao****1972
  • 文档编号:84153814
  • 上传时间:2019-03-03
  • 文档格式:DOC
  • 文档大小:44.50KB
  • / 2 举报 版权申诉 马上下载
  • 文本预览
  • 下载提示
  • 常见问题
    • 截取字符串在项目中,经常显示时候要截取字符.一直用的是substring这个方法,由于汉字和字符截取时候默认长度一样,造成有时侯截显示长度不一样.后来根据字符来截取,下面是使用的代码import java.io.UnsupportedEncodingException;public class CutString { /** * 判断是否是一个中文汉字 * * @param c * 字符 * @return true表示是中文汉字,false表示是英文字母 * @throws UnsupportedEncodingException * 使用了JAVA不支持的编码格式 */ public static boolean isChineseChar(char c) throws UnsupportedEncodingException { // 如果字节数大于1,是汉字,以这种方式区别英文字母和中文汉字并不是十分严谨 return String.valueOf(c).getBytes("GBK").length > 1; } /** * 按字节截取字符串 * * @param orignal * 原始字符串 * @param count * 截取位数 * @return 截取后的字符串 * @throws UnsupportedEncodingException * 使用了JAVA不支持的编码格式 */ public static String substring(String orignal, int count) throws UnsupportedEncodingException { // 原始字符不为null,也不是空字符串 if (orignal != null && !"".equals(orignal)) { // 将原始字符串转换为GBK编码格式 orignal = new String(orignal.getBytes(), "GBK"); // 要截取的字节数大于0,且小于原始字符串的字节数 if (count > 0 && count < orignal.getBytes("GBK").length-2) { StringBuffer buff = new StringBuffer(); char c; for (int i = 0; i < count; i++) { c = orignal.charAt(i); buff.append(c); if (CutString.isChineseChar(c)) { // 遇到中文汉字,截取字节总数减1 --count; } } buff.append(".."); return buff.toString(); } } return orignal; }/** * 测试方法* / public static void main(String[] args) { } }} 2 / 2。

      点击阅读更多内容
      关于金锄头网 - 版权申诉 - 免责声明 - 诚邀英才 - 联系我们
      手机版 | 川公网安备 51140202000112号 | 经营许可证(蜀ICP备13022795号)
      ©2008-2016 by Sichuan Goldhoe Inc. All Rights Reserved.