A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© qq272936993 初级黑马   /  2014-11-13 20:33  /  853 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class DbcSbcUtils {

  2.         /**
  3.          * 半角、全角字符判断
  4.          * @param c 字符
  5.          * @return true:半角; false:全角
  6.          */
  7.         public static boolean isDbcCase(char c) {
  8.                 // 基本拉丁字母(即键盘上可见的,空格、数字、字母、符号)
  9.                 if (c >= 32 && c <= 127) {
  10.                         return true;
  11.                 }
  12.                 // 日文半角片假名和符号
  13.                 else if (c >= 65377 && c <= 65439) {
  14.                         return true;
  15.                 }
  16.                 return false;
  17.         }

  18.         /**
  19.          * 字符串长度取得(区分半角、全角)
  20.          * @param str 字符串
  21.          * @return 字符串长度
  22.          */
  23.         public static int getLength(String str) {
  24.                 int len = 0;
  25.                 for (int i = 0; i < str.length(); i++) {
  26.                         char c = str.charAt(i);
  27.                         if (isDbcCase(c)) { // 半角
  28.                                 len = len + 1;
  29.                         } else { // 全角
  30.                                 len = len + 2;
  31.                         }
  32.                 }
  33.                 return len;
  34.         }

  35.         /**
  36.          * 字符串截取(区分半角、全角)
  37.          * @param str  字符串
  38.          * @param limit 长度
  39.          * @return
  40.          */
  41.         public static String left(String str, int limit) {
  42.                 if (getLength(str) <= limit) {
  43.                         return str;
  44.                 }
  45.                 char[] chars = str.toCharArray();
  46.                 int charLenSum = 0;
  47.                 String result = "";
  48.                 for (int i = 0; i < chars.length; i++) {
  49.                         int charLen = isDbcCase(chars[i]) ? 1 : 2;
  50.                         if (charLenSum + charLen > limit) {
  51.                                 return result;
  52.                         }
  53.                         charLenSum += charLen;
  54.                         result += chars[i];
  55.                         if (charLenSum == limit) {
  56.                                 return result;
  57.                         }
  58.                 }
  59.                 return "";
  60.         }

  61.         public static void main(String[] args) {
  62.                 System.out.println(left("全角文字", 10));
  63.                 System.out.println(left("全角文字判", 10));
  64.                 System.out.println(left("全角文字12", 10));
  65.                 System.out.println(left("全角文字123", 10));
  66.                 System.out.println(left("全角文字判a", 10));
  67.                 System.out.println(left("全角文字判断", 10));
  68.         }
  69. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马