Large string split into lines with maximum length in java

后端 未结 8 1260
[愿得一人]
[愿得一人] 2020-12-01 08:09
String input = \"THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this s         


        
8条回答
  •  执念已碎
    2020-12-01 08:45

    Thanks Barend Garvelink for your answer. I have modified the above code to fix the Bug: "if a word in the input is longer than maxCharInLine"

    public String[] splitIntoLine(String input, int maxCharInLine){
    
        StringTokenizer tok = new StringTokenizer(input, " ");
        StringBuilder output = new StringBuilder(input.length());
        int lineLen = 0;
        while (tok.hasMoreTokens()) {
            String word = tok.nextToken();
    
            while(word.length() > maxCharInLine){
                output.append(word.substring(0, maxCharInLine-lineLen) + "\n");
                word = word.substring(maxCharInLine-lineLen);
                lineLen = 0;
            }
    
            if (lineLen + word.length() > maxCharInLine) {
                output.append("\n");
                lineLen = 0;
            }
            output.append(word + " ");
    
            lineLen += word.length() + 1;
        }
        // output.split();
        // return output.toString();
        return output.toString().split("\n");
    }
    

提交回复
热议问题