简体   繁体   English

使用换行符将字符串中的行限制为 60 个字符

[英]Limit line in the string to 60 characters with newlines

The program was made to delete double, triple ... spaces from the string and limit characters to 60 per line.该程序旨在从字符串中删除双倍、三倍...空格并将字符限制为每行 60 个。

The problem is it gets words into lines that are in the 60th position when the idea is it must skip them.问题是当它必须跳过它们时,它会将单词放入第 60 个位置的行中。

Output is:输出是:

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.

but the correct output must be:但正确的输出必须是:

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.

My code so far:到目前为止我的代码:


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

Here are the results of my 24th test run.这是我第 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.

The first paragraph is the input.第一段是输入。 The second paragraph is the output.第二段是输出。

Take a look at the code.看一下代码。 Do you see several commented out System.out.println statements?你看到几个注释掉的System.out.println语句了吗? That's how you find problems with your code.这就是您发现代码问题的方式。 You write a few lines of code, then you print the intermediate results.您编写几行代码,然后打印中间结果。 Rinse and repeat until your code works.冲洗并重复,直到您的代码有效。

Here's the complete runnable code.这是完整的可运行代码。

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

}

Here you go.干得好。 After your replace.更换后。 Not very efficient, but it should to the trick.效率不高,但应该能解决问题。

    int pos = 0;
    StringBuilder stringBuilder = new StringBuilder(text);
    String finalText = recursiveBuild(stringBuilder,  pos).toString();
    System.out.println(finalText);
}

private static StringBuilder recursiveBuild(StringBuilder stringBuilder, int pos) {
    if (pos+60<stringBuilder.length()){
        if (pos == 0) pos+=60;
        int tempPos = stringBuilder.substring(0, pos).lastIndexOf(" ");
        stringBuilder.delete(tempPos, tempPos+1).insert(tempPos, "\n");
        stringBuilder = recursiveBuild(stringBuilder, tempPos+60);
    } else {
        int tempPos = stringBuilder.substring(0, pos).lastIndexOf(" ");
        stringBuilder.delete(tempPos, tempPos+1).insert(tempPos, "\n");
    }
    return stringBuilder;
}

Only works for只适用于

        String text = "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.";

Hopefully you'll find an all regex "almost one liner" answer interesting (note requires JDK9+).希望您会发现所有正则表达式“几乎是一个班轮”的答案很有趣(注意需要 JDK9+)。 This borrows the cleaned up temp string from @Gilbert Le Blanc answer but appends space so that every word ends with just single space:这从@Gilbert Le Blanc 的答案中借用了清理过的temp字符串,但附加了空格,以便每个单词都以一个空格结尾:

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.";
System.out.format("%ntext:%n%s%n", text);

String temp = text.replaceAll("\\s{1,}", " ").trim()+" ";
System.out.format("%ntemp:%n%s%n", temp);

Then another regex with replaceAll(Function<MatchResult, String> replacer) can be used to split complete words up to 60 characters a line when the last letter matched isn't a space:然后replaceAll(Function<MatchResult, String> replacer)当匹配的最后一个字母不是空格时,另一个带有replaceAll(Function<MatchResult, String> replacer)正则表达式可用于将完整的单词拆分为每行最多 60 个字符:

// Word wrap at 60th:
String word60 = Pattern.compile("(.{0,59}[^ ])[ $]").matcher(temp)
                       .replaceAll(mr -> mr.group().trim()+System.lineSeparator());
System.out.format("%nword60:%n%s%n", word60);

Printing:印刷:

text:
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.

temp:
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. 

word60:
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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM