public static String[] parseTxt(String text, int width, Font font,
char newLine) {
Vector vector = new Vector();
int offset = 0;
int maxLength = text.length(); // 字符串总长度
boolean endFlag; // 标记是否已经换行
while (offset < maxLength) {
if (text.charAt(offset) == newLine) {
// 如果第一个字符是换行符,添加一个空串,偏移值加一,继续检索
vector.addElement("");
offset++;
} else {
endFlag = false;
for (int i = 1; offset + i < maxLength; i++) {
if (text.charAt(offset + i) == newLine) {
// 遇到换行符,添加子串
int diff = offset + i;
if (newLine == '\n') {
diff += 1;
}
vector.addElement(text.substring(offset, diff));
offset += i + 1;
endFlag = true;
break;
} else if (font.charsWidth(text.toCharArray(), offset,
i + 1) > width) {
// 子串长度大于指定宽度,终止搜索,添加子串
if (i >= 2 && isLetter(text.charAt(offset + i))
&& isLetter(text.charAt(offset + i - 1))) {
// 判断结束相关的3个字符类型为字母,则添加换行连接符”-“
if (isLetter(text.charAt(offset + i - 2)))
vector.addElement(text.substring(offset, offset + i - 1) + "-");
else
vector.addElement(text.substring(offset, offset+ i - 1));
offset += (i - 1);
} else {
vector.addElement(text
.substring(offset, offset + i));
offset += i;
}
endFlag = true;
break;
}
}
if (!endFlag) {
// 搜索到整个原始串的结尾时,添加剩余的部分
vector.addElement(text.substring(offset));
break;
}
}
}
int size = vector.size();
String[] txt = new String[size];
for (int i = 0; i < size; i++)
txt[i] = ((String) vector.elementAt(i));
return txt;
}
// 字母ASCII码,A-Z:65-90,a-z:97-122
public static boolean isLetter(char c){
if((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
return true;
return false;
}
处理中英文切割字符串的方法
最新推荐文章于 2022-08-26 18:40:55 发布