Java String Split by Space splitOnSpace(final String string)

Here you can find the source of splitOnSpace(final String string)

Description

Splits the given string on spaces, which is faster than String.split(...) for this special case.

License

Open Source License

Parameter

Parameter Description
string the given string

Return

the words that compose the string

Declaration

public static List<String> splitOnSpace(final String string) 

Method Source Code

//package com.java2s;
/*/*from   w  w w .j  a va  2  s . com*/
 * StringUtils.java
 *
 * Created on October 4, 2006, 2:36 PM
 *
 * Description:
 *
 * Copyright (C) 2006 Stephen L. Reed.
 *
 * This program is free software; you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    /** Splits the given string on spaces, which is faster than String.split(...) for this special case.
     *
     * @param string the given string
     * @return the words that compose the string
     */
    public static List<String> splitOnSpace(final String string) {
        final List<String> words = new ArrayList<>();
        final int string_len = string.length();
        int index = 0;
        for (int i = 0; i < string_len; i++) {
            final char ch = string.charAt(i);
            if (ch == ' ') {
                if (i > index) {
                    words.add(string.substring(index, i));
                }
                index = i + 1;
            }
        }
        if (index < string_len) {
            words.add(string.substring(index));
        }
        return words;
    }
}

Related

  1. splitAndKeepEscapedSpaces(String string, boolean preserveEscapes)
  2. splitAtSpaces(String s)
  3. splitBySpace(String p_str)
  4. splitInWhiteSpaces(String string)
  5. splitNamespaceTitle(String fullTitle)
  6. splitOnSpace(String string)
  7. SplitOnWhitespace(String instrData)
  8. splitSpaces(String input)
  9. splitStringOnWhitespace(String text)