标签:
最近在实现一个文稿导读功能时候用到字符串切割,简单说一下这个文稿导读,就是打开本地一个txt文件,展示在界面上,提供一个开始/暂停的button。开始,文本自动移动变红,速度自己可以控制,就是像歌词那样,一行一行的自动移动,变色的一行始终是展示的控件的中间。为什么用到字符串的切割呢?是因为不用分辨率和不同尺寸的屏幕显示字的个数是不一样的。在实现的时候我就想到根据展示控件(这里是自定义的TextView)的大小串来切割字符串的,以适应不同设备。在下一篇文章中实现这个“文稿导读”的功能,这一片文章先用来讲解切割字符串的方法;
从一个文本中取出来的字符串,可能是纯中文文本,也有可能是中英混合的。
纯中文文本的请情况下,使用一种比较容易理解的方式来实现:
/**
* 按照指定长度切割字符串
* @param inputString 需要切割的源字符串
* @param length 指定的长度
* @return
*/
public static List<String> getDivLines(String inputString, int length) {
List<String> divList = new ArrayList<>();
int remainder = (inputString.length()) % length;
// 一共要分割成几段
int number = (int) Math.floor((inputString.length()) / length);
for (int index = 0; index < number; index++) {
String childStr = inputString.substring(index * length, (index + 1) * length);
System.out.println(childStr);
divList.add(childStr);
}
if (remainder > 0) {
String cStr = inputString.substring(number * length, inputString.length());
divList.add(cStr);
}
return divList;
} 通用(中英混合或者纯中文,英文)的一种方式:
/**
* 处理输入的字符串,将字符串分割成以byteLength为宽度的多行字符串。
* 根据需要,英文字符的空格长度为0.5,汉字的长度为2(GBK编码下,UTF-8下为3),数字英文字母宽度为1.05。
* @param inputString 输入字符串
* @param byteLength 以byteLength的长度进行分割(一行显示多宽)
* @return 处理过的字符串
*/
public static String getChangedString(String inputString, int byteLength) {
String outputString = inputString;
try {
char[] chars = inputString.toCharArray();
char[] workChars = new char[chars.length * 2];
// i为工作数组的角标,length为工作过程中长度,stringLength为字符实际长度,j为输入字符角标
int i = 0, stringLength = 0;
float length = 0;
for (int j = 0; j < chars.length - 1; i++, j++) {
// 如果源字符串中有换行符,此处要将工作过程中计算的长度清零
if (chars[j] == '\n') {
length = 0;
}
try {
workChars[i] = chars[j];
//对汉字字符进行处理
if (new Character(chars[j]).toString().getBytes("GBK").length == 2 /*&& chars[j] != '”' && chars[j] != '“'*/) {
length++;
if (length >= byteLength) {
if (chars[j + 1] != '\n') {
i++;
stringLength++;
workChars[i] = '\n';
}
length = 0;
}
} else if (new Character(chars[j]).toString().getBytes("GBK").length == 1) {
//对空格何应为字符和数字进行处理。
if (chars[j] == ' ' ) {
length -= 0.5;
}else {
length += 0.05;
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stringLength++;
length++;
//长度超过给定的长度,插入\n
if (length >= byteLength) {
if (chars[j + 1] != '\n') {
i++;
stringLength++;
workChars[i] = '\n';
}
length = 0;
}
}
outputString = new String(workChars).substring(0, stringLength)/* .trim() */;
System.out.println(outputString);
} catch (Exception e) {
// TODO: handle exception
Log.e("TextViewHelper", e.toString());
}
return outputString;
}
在解决这个问题的过程中,尝试着其他的一些方法,虽然没有实现,但是在解决问题的过程中感觉到,只要你想到的对字符串的操作,API里面基本都有,因为他们考虑到的很全面,对字符串的操作一般在文档中就有对应的API。多上网找资料,找不到就去在API中查找,问题总会有解决的方法。
版权声明:本文为博主原创文章,未经博主允许不得转载。
Java 按照指定长度分割字符串(一种是纯英文字符串,一种是英汉混合的字符串)
标签:
原文地址:http://blog.csdn.net/zq13561411965/article/details/48003297