Java String Break breakString(String str, int maxLineLenght)

Here you can find the source of breakString(String str, int maxLineLenght)

Description

Break a string into lines with maximum length of maxLineLenght.

License

Open Source License

Parameter

Parameter Description
str The string to be breaked
maxLineLenght The maximum length of the string

Return

The breaked string

Declaration

public static String breakString(String str, int maxLineLenght) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**Break a string into lines with maximum length of maxLineLenght.
     * The function insert a line break after the next blank space
     * found into the string, at every maxLineLength characters.
     * /*  w  w  w .j a va2s  . c om*/
     * @param str The string to be breaked
     * @param maxLineLenght The maximum length of the string
     * @return The breaked string  */
    public static String breakString(String str, int maxLineLenght) {
        StringBuffer sb = new StringBuffer();
        int pos = 0;
        for (int i = 0; i < str.length(); i++) {
            sb.append(str.charAt(i));
            if (++pos > maxLineLenght) {
                if (str.charAt(i) == ' ') {
                    sb.append('\n');
                    pos = 0;
                }
                //if anyone blank char be found at the next 20 characters
                //after the maxLineLenght, break string anyway.
                else if (Math.abs(pos - maxLineLenght) > 20) {
                    sb.append('\n');
                    pos = 0;
                }
            }
        }
        return sb.toString();
    }
}

Related

  1. breakString(String input, int partLength)
  2. breakString(String remainingStr, String soFar, int maxLineLength)
  3. breakString(String string, int l, String newLine)
  4. breakString(String text, int maxsize)
  5. breakString(String theString)