Java String Split by Length splitString(String string, int maxCharsPerLine)

Here you can find the source of splitString(String string, int maxCharsPerLine)

Description

Splits a string into multiple lines, each with at most maxChars characters.

License

BSD License

Parameter

Parameter Description
string a parameter
maxCharsPerLine a parameter

Return

a List of Strings representing the lines.

Declaration

public static List<String> splitString(String string, int maxCharsPerLine) 

Method Source Code

//package com.java2s;
/**/*from  w  w w  .  jav  a2s.  c  o  m*/
 * Manipulate and analyze Strings.
 * 
 * <p>
 * <span class="BSDLicense"> This software is distributed under the <a
 * href="http://hci.stanford.edu/research/copyright.txt">BSD License</a>. </span>
 * </p>
 * 
 * @author <a href="http://graphics.stanford.edu/~ronyeh">Ron B Yeh</a> (ronyeh(AT)cs.stanford.edu)
 */

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     * Splits a string into multiple lines, each with at most maxChars characters. We will try our best to
     * split after spaces.
     * 
     * @param string
     * @param maxCharsPerLine
     * @return a List of Strings representing the lines.
     */
    public static List<String> splitString(String string, int maxCharsPerLine) {
        final List<String> lines = new ArrayList<String>();
        final String[] items = string.split(" ");
        final StringBuilder currString = new StringBuilder();
        for (String item : items) {
            if (currString.length() + item.length() > maxCharsPerLine) {
                lines.add(currString.toString());
                currString.setLength(0); // clear buffer
            }
            currString.append(item + " ");
        }
        lines.add(currString.toString());
        return lines;
    }
}

Related

  1. splitPreserveAllTokens(String str, String separatorChars, int max)
  2. splitString(String orig, String delim, int max)
  3. splitString(String s, int maxSize)
  4. splitString(String str, int length)
  5. splitString(String str, int length)
  6. splitString(String stringToSplit, int maxLength)
  7. splitStringByLength(String input, int length)
  8. splitStringFixedLen(String data, int interval)
  9. splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens)