Break the textArea's text into lines along words. - Java java.lang

Java examples for java.lang:String New Line

Description

Break the textArea's text into lines along words.

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String originalString = "this is a test. Break the textArea's text into lines along words. Algorithm copied from:";
        int maxLineLength = 42;
        System.out.println(splitStringAlongWords(originalString,
                maxLineLength));//from  w w  w .j  a va  2s . co  m
    }

    /**
     * Break the textArea's text into lines along words. Algorithm copied from:
     * http://www.java-forums.org/new-java/4669-how-split-string-into-multiple-lines-x-characters-each.html
     *
     * @param originalString the original string text that will be broken
     * @return the broken string as a list of strings
     */
    public static List<String> splitStringAlongWords(String originalString,
            int maxLineLength) {
        List<String> broken = new ArrayList<String>();
        char[] chars = originalString.toCharArray();
        boolean endOfString = false;
        int start = 0;
        int end;
        while (start < chars.length - 1) {
            int charCount = 0;
            int lastSpace = 0;
            while (charCount < maxLineLength) {
                if (chars[charCount + start] == '\n') {
                    lastSpace = charCount;
                    break;
                } else if (chars[charCount + start] == ' ') {
                    lastSpace = charCount;
                }
                charCount++;
                if (charCount + start == originalString.length()) {
                    endOfString = true;
                    break;
                }
            }
            end = endOfString ? originalString.length()
                    : (lastSpace > 0) ? lastSpace + start : charCount
                            + start;
            broken.add(originalString.substring(start, end));
            start = end + 1;
        }
        return broken;
    }
}

Related Tutorials