import java.io.UnsupportedEncodingException;
public class test {
public static String cutStringByLen(String s,int maxLength) throws UnsupportedEncodingException{
//返回值赋值
String rs = "";
//判断为空或者小于40直接返回原来字符串
if(s.isEmpty() || s.getBytes("GBK").length<40) {
System.out.println("实际最大可返回长度:"+s.getBytes("GBK").length);
return s;
}
//去掉空格
//s = s.replaceAll(" ","");
//转换成char数组
char[] charArray = s.toCharArray();
//长度计数初始化
int count = 0;
for(char ch : charArray) {
//将char转换为string并获取长度,字符指定GBK
int length = String.valueOf(ch).getBytes("GBK").length;
//存储当前返回值,用于返回超过40个字符且不等于40个字符情况
String tempRs = rs;
//拼接返回值
rs = rs + ch;
//存储当前计算长度之前的长度,用于返回超过40个字符且不等于40个字符情况
int countBefor = count;
//累加长度
count = count + length;
if(count == maxLength) {
break;
}
if(count>maxLength) {
//maxLength = countBefor;
rs = tempRs;
break;
}
}
System.out.println("实际最大可返回长度:"+ maxLength);
return rs;
}
//测试
public static void main(String[] args) throws UnsupportedEncodingException {
//超过40字符,且存在中文标点和空格,其他符号
String s ="匹电宝,匹电宝 - 比喻框架盛祥-胡能!及!图2皮把3司";
String s1 = "匹电宝,匹电宝 - 公用事业缴111-湘普!人!";
String s2 ="匹电宝,匹电宝 - 公用规划时皮-湘22!!";
System.out.println("超过40字符,且存在中文标点和空格,其他符号:" + cutStringByLen(s,40));
System.out.println("等于40字符,且存在中文标点和空格,其他符号:" + cutStringByLen(s1,40));
System.out.println("小于40字符,且存在中文标点和空格,其他符号:" + cutStringByLen(s2,40));
}
}