/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @return String
* @author ivan
* @since 2010.07.05
*/
public static String splitString(String str, int len) {
return splitString(str, len, "...");
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @param elide 省略符
* @return String
* @author ivan
* @since 2010.07.05
*/
public static String splitString(String str,int len,String elide) {
if (str == null) {
return "";
}
byte[] strByte = str.getBytes();
int strLen = strByte.length;
//int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;
int elideLen = 0;
if (len >= strLen || len < 1) {
return str;
}
if (len - elideLen > 0) {
len = len - elideLen;
}
int count = 0;
for (int i = 0; i < len; i++) {
int value = (int) strByte[i];
if (value < 0) {
count++;
}
}
if (count % 2 != 0) {
len = (len == 1) ? len + 1 : len - 1;
}
return new String(strByte, 0, len) + elide.trim();
}
转
http://blgaici1.iteye.com/blog/723255
public static String subStr(String str, int num) {
int max = num;
try {
max = trimGBK(str.getBytes("GBK"),num);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int sum = 0;
if (str != null && str.length() > max) {
StringBuilder sb = new StringBuilder(max);
for (int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
// if ((c & 0xff00) != 0)
// sum += 2;
// else
sum += 1;
if (sum <= max)
sb.append((char) c);
else
break;
}
return sb.append("...").toString();
} else
return str != null ? str : "";
}
public static int trimGBK(byte[] buf,int n){
int num = 0;
boolean bChineseFirstHalf = false;
if(buf.length < n )return buf.length;
for(int i=0;i<n;i++)
{
if(buf[i]<0 && !bChineseFirstHalf){
bChineseFirstHalf = true;
}else{
num++;
bChineseFirstHalf = false;
}
}
return num;
}
分享到:
相关推荐
批量统计多字符串中[中英文标点数量],根据给定gbk/utf编码,计算出总长度。若总长度超过给定(最大)长度,则自动截取。使用场景:配合注解以及aop,解决录入数据库超长会报错的情况。
判断字符串为空 判断Email有效性 判断身份证号码有效性 判断手机号码有效性 判断是否含有特殊字符 ...截取字符串从开始到给定长度的一段 判断字符串是否以某个前缀开头 判断字符串是否以某个后缀结尾
判断一个字符是Ascill字符还是其它字符(如汉,日,...得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1 截取一段字符的长度,不区分中英文,如果数字不正好,则少取一个字符位 生成随机字符串
返回字符串中字符的个数,即长度。中文、英文都算作一个字符。 其语法形式如下:字符串名.length(); 例1:在某系统中对管理员密码有这样的规定,即密码长度不得少于6位。 获取字符串的长度 public static void main...
六、将一个字符里出现最多的字母截取,如,addcbbs变为acs。 七、输入一个整型数组,arr=(1,2,5) 输出数组中数字对应英文字母表中对应的字母,如果不在字母表中用"?"表示 例如,输入...
1)int length():该方法用来获取当前字符串的字符数量,无论中文还是英文每个字符都是1个长度 2)int indexOf(String str):查看给定字符串在当前字符串中的位置。 首先该方法会使用给定的字符串与当前字符串进行...
18.如何计算中英文混合字符串的长度 19.如何判断字符串是否以指定字符串开头或结尾 20.如何判断字符是否是英文字符 21.如何检测字符串出现的次数 22.如何过滤字符串中的HTML代码 23.如何截取字符串 24.如何实现字符...
System.out.println("数据长度:"+len); left = 0; right = len - 1; while (left ) { //由于源数据不是顺序的,需先进行排序 int temp; for(int i=0;i;++i) { for(int j=0;j;++...
且具有智能标题截取功能:由于英文和数字是半角字符,而中文汉字是全角,当标题中经常出现这两种混杂,又不愿意采用精简标题的情况下,强制截取长度会影响页面美观。智能截取会主动判断每一个字符是全角或半角,会...
OpenGL支持库中的部分英文名称常量已改为中文,并统一在所有常量名称之前加前缀“GL_”,以减少与其它库的冲突机率。 3. 互联网支持库中的“FTP目录列表”命令返回的文件时间改为FTP服务器返回的原始时间,不做...