子兮子兮 子兮子兮

No can, but will.

目录
提问:以下 Java 代码如何精简,或用其他语言用尽可能少的代码来实现
/      

提问:以下 Java 代码如何精简,或用其他语言用尽可能少的代码来实现

1. 功能要求

实现传入一个字符串,指定每行的长度,返回换行后的字符串(可忽略参数 endStr,特殊尾行不处理换行)。传入的参数可能是任意的,代码中需防止出现空指针和下标越界等异常。
可以直接精简此 Java 代码或使用 C、Go、Python 等你喜欢的任一种编程语言。
因为自己用 Java 实现后感觉实在是太啰嗦了,故有此问。

2. Java 代码

 1    /**
 2     * 处理字符串自动换行
 3     * @param lineLength 每行长度
 4     * @param inStr 待转换字符串
 5     * @param lineSepar 换行符
 6     * @param endStr 最后一行
 7     * @return 处理后的字符串
 8     */
 9    public static String wordWrapData(int lineLength, String inStr, String lineSepar, String endStr) {
10        if (inStr == null && endStr == null) {
11            return "";
12        }
13        lineSepar = lineSepar == null ? System.getProperty("line.separator") : lineSepar;
14        StringBuilder outStr = new StringBuilder(128);
15        boolean enable = inStr != null && inStr.length() > lineLength && lineLength > 0;
16        int i = 0, newLength = lineLength, length = (inStr == null ? 0 : inStr.length());
17        for (; enable && i < length - lineLength; newLength += lineLength, i += lineLength) {
18            outStr.append(inStr.substring(i, newLength)).append(lineSepar);
19            if (newLength < length && (newLength + lineLength) > length) {
20                outStr.append(inStr.substring(newLength, length));
21            }
22        }
23        if (!enable && inStr != null) {
24            outStr.append(inStr);
25        }
26        if (endStr != null) {
27            outStr.append(lineSepar).append(endStr);
28        }
29        return outStr.toString();
30    }
31
32    /**
33     * TEST
34     * @param args
35     */
36    public static void main(String[] args) {
37        String test = "1234567890123456789012345678901234567890";
38        System.out.println(wordWrapData(test, "\r\n", "", 18));
39        System.out.println(wordWrapData(test, null, null, 0));
40        System.out.println(wordWrapData(null, null, null, 18));
41        System.out.println(wordWrapData("只有第一行", null, null, 18));
42        System.out.println(wordWrapData(null, null, "只有最后一行", 18));
43        System.out.println(wordWrapData("第一行", null, "最后一行", 18));
44    }

3. 执行结果

第一次调用:

1123456789012345678
2901234567890123456
37890

第二次调用:

11234567890123456789012345678901234567890

第三次调用:

1

第四次调用:

1只有第一行

第五次调用:

1只有最后一行

第六次调用:

1第一行
2最后一行



我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=wh4u6zpyhe1d