处理中英文切割字符串的方法

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;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值