首页 > 解决方案 > 使用换行符将字符串中的行限制为 60 个字符

问题描述

该程序用于从字符串中删除双倍、三倍……空格,并将字符限制为每行 60 个。

问题是当想法是它必须跳过它们时,它会将单词放入第 60 位的行中。

输出是:

Java was originally developed by James Gosling at Sun Microsystems
(which has since been acquired by Oracle) and released in 1995
as a core component of Sun Microsystems' Java platform.

但正确的输出必须是:

Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and
released in 1995 as a core component of Sun Microsystems'
Java platform.

到目前为止我的代码:


      StringBuilder sb = new StringBuilder(text.replaceAll("(^ )|( $)", "").replaceAll("\\s{2,}", " "));
       int i = 0;
       while ((i = sb.indexOf(" ", i + 60)) != -1) {
           sb.replace(i,i+1,"\n");
       }
       String result = sb.toString();
       return result;
   }

标签: javastringreplacenewlinestringbuilder

解决方案


这是我第 24 次试运行的结果。

Java was originally developed by James Gosling at Sun Microsystems
(which has since been acquired by Oracle) and released in 1995
as a core component of Sun Microsystems'   Java platform.

Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and
released in 1995 as a core component of Sun Microsystems'
Java platform.

第一段是输入。第二段是输出。

看一下代码。你看到几个被注释掉的System.out.println语句吗?这就是您发现代码问题的方式。您编写几行代码,然后打印中间结果。冲洗并重复,直到您的代码有效。

这是完整的可运行代码。

public class FixedLengthLines {

    public static void main(String[] args) {
        new FixedLengthLines().processString();
    }
    
    public void processString() {
        String text = "Java was originally developed by James Gosling at Sun Microsystems\r\n" + 
                "(which has since been acquired by Oracle) and released in 1995\r\n" + 
                "as a core component of Sun Microsystems'   Java platform.";
        String temp = text.replaceAll("\\s{2,}", " ");
//      System.out.println(temp);
        
        int lineLength = 60;
        int lineIndex = 0;
        int endIndex = Math.min(lineIndex + lineLength, temp.length());
        StringBuilder builder = new StringBuilder();
        
        while (lineIndex < endIndex) {
//          System.out.println(lineIndex + " " + endIndex + " " + temp.length());
            
            if (endIndex >= lineIndex + lineLength) {
                endIndex = temp.lastIndexOf(" ", endIndex); 
            }
            
            builder.append(temp.substring(lineIndex, endIndex));
            builder.append(System.lineSeparator());
            
//          System.out.println(endIndex + " " + temp.substring(lineIndex, endIndex));
            
            lineIndex = endIndex + 1;
            endIndex = Math.min(lineIndex + lineLength, temp.length());
        }
        
        System.out.println(text);
        System.out.println();
        System.out.println(builder.toString());
    }

}

推荐阅读