文章目录
  1. 1. 分析
  2. 2. 代码

如何将一行太长的字符串分割成多行?

分析

首先我们需要考虑中文字符的情况,一个汉字 getBytes().length == 2

  1. 判断一个字符是否中文字符的方法如下:

    1
    2
    3
    public static boolean isChineseChar(char ch) throws UnsupportedEncodingException{
    return String.valueOf(ch).getBytes("GBK").length >1;
    }
  2. 遍历字符串,遇到英文字符计数加1,遇到中文字符计数加2。当计数大于或等于每行要求的字符数时,添加换行符并重置计数。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 将一行字符串以固定字节(非字符)长度分成多行显示。每行显示的字符至多为<code>numbersPerLine+1</code>
* @param source 原字串
* @param numbersPerLine 每行的字节数, 如果是负数,则看成无穷大,返回原字串
* @return 在合适位置添加了换行符的字串
* @throws UnsupportedEncodingException
*/
public static String divideIntoMultiLines(String source,int numbersPerLine)
throws UnsupportedEncodingException{
if (null == source ) {
return null;
}

int gbkLen = source.getBytes("GBK").length;
if (gbkLen <= numbersPerLine || numbersPerLine <=0) {
return source;
}
int countOfLines = (gbkLen - 1) / numbersPerLine +1 ;
StringBuilder sb = new StringBuilder(gbkLen + countOfLines-1);
int count = 0;
char ch;
int len = source.length();
for (int i = 0; i < len ; i++) {
ch = source.charAt(i);
count++;
if (isChineseChar(ch)) {
count++;//中文字符占两个字节
}
sb.append(ch);
if (count >= numbersPerLine) {//完成一行分割
count = 0 ;
sb.append('\n');
}
}
return sb.toString();
}
文章目录
  1. 1. 分析
  2. 2. 代码