Java String Split by Space splitInWhiteSpaces(String string)

Here you can find the source of splitInWhiteSpaces(String string)

Description

Splits the given string in a list where each element is a line.

License

Open Source License

Parameter

Parameter Description
string string to be split.

Return

list of strings where each string is a line.

Declaration

public static List<String> splitInWhiteSpaces(String string) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * Copyright (C) 2012-2013  Fabio Zadrozny and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  w  w  w  . java 2 s.  c  o  m
 *     Fabio Zadrozny <fabiofz@gmail.com>    - initial API and implementation
 *     Jonah Graham <jonah@kichwacoders.com> - ongoing maintenance
 ******************************************************************************/

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Splits the given string in a list where each element is a line.
     *
     * @param string string to be split.
     * @return list of strings where each string is a line.
     *
     * @note the new line characters are also added to the returned string.
     */
    public static List<String> splitInWhiteSpaces(String string) {
        ArrayList<String> ret = new ArrayList<String>();
        int len = string.length();

        int last = 0;

        char c = 0;

        for (int i = 0; i < len; i++) {
            c = string.charAt(i);
            if (Character.isWhitespace(c)) {
                if (last != i) {
                    ret.add(string.substring(last, i));
                }
                while (Character.isWhitespace(c) && i < len - 1) {
                    i++;
                    c = string.charAt(i);
                }
                last = i;
            }
        }
        if (!Character.isWhitespace(c)) {
            if (last == 0 && len > 0) {
                ret.add(string); //it is equal to the original (no char to split)

            } else if (last < len) {
                ret.add(string.substring(last, len));

            }
        }
        return ret;
    }
}

Related

  1. split(String source, String limit, boolean trim, boolean ignoreWhitespace)
  2. splitAndKeepEscapedSpaces(String string, boolean preserveEscapes)
  3. splitAtSpaces(String s)
  4. splitBySpace(String p_str)
  5. splitNamespaceTitle(String fullTitle)
  6. splitOnSpace(final String string)
  7. splitOnSpace(String string)
  8. SplitOnWhitespace(String instrData)