Large string split into lines with maximum length in java

后端 未结 8 1239
[愿得一人]
[愿得一人] 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:30

    My version(The previous were not working)

    public static List breakSentenceSmart(String text, int maxWidth) {
    
        StringTokenizer stringTokenizer = new StringTokenizer(text, " ");
        List lines = new ArrayList();
        StringBuilder currLine = new StringBuilder();
        while (stringTokenizer.hasMoreTokens()) {
            String word = stringTokenizer.nextToken();
    
            boolean wordPut=false;
            while (!wordPut) {
                if(currLine.length()+word.length()==maxWidth) { //exactly fits -> dont add the space
                    currLine.append(word);
                    wordPut=true;
                }
                else if(currLine.length()+word.length()<=maxWidth) { //whole word can be put
                    if(stringTokenizer.hasMoreTokens()) {
                        currLine.append(word + " ");
                    }else{
                        currLine.append(word);
                    }
                    wordPut=true;
                }else{
                    if(word.length()>maxWidth) {
                        int lineLengthLeft = maxWidth - currLine.length();
                        String firstWordPart = word.substring(0, lineLengthLeft);
                        currLine.append(firstWordPart);
                        //lines.add(currLine.toString());
                        word = word.substring(lineLengthLeft);
                        //currLine = new StringBuilder();
                    }
                    lines.add(currLine.toString());
                    currLine = new StringBuilder();
                }
    
            }
            //
        }
        if(currLine.length()>0) { //add whats left
            lines.add(currLine.toString());
        }
        return lines;
    }
    

提交回复
热议问题