Java String Split by Space splitAtSpaces(String s)

Here you can find the source of splitAtSpaces(String s)

Description

Splits a string separated by space characters.

License

Creative Commons License

Parameter

Parameter Description
s a string. Can be null.

Return

an array of all items separated by spaces. If string is null or empty, returns an empty array.

Declaration

public static String[] splitAtSpaces(String s) 

Method Source Code


//package com.java2s;
import java.util.ArrayList;

public class Main {
    private static final String[] emptyStringArray = new String[0];

    /**//from  ww  w.j  a  va 2  s.  com
     * 
     * Splits a string separated by space characters.
     * This method acts as though it strips leading and
     * trailing space
     * characters from the string before splitting it.
     * The space characters are
     * U+0009, U+000A, U+000C, U+000D, and U+0020.
     * 
     * @param s a string. Can be null.
     * @return an array of all items separated by spaces. If string
     * is null or empty, returns an empty array.
     */
    public static String[] splitAtSpaces(String s) {
        if (s == null || s.length() == 0)
            return emptyStringArray;
        int index = 0;
        int sLength = s.length();
        while (index < sLength) {
            char c = s.charAt(index);
            if (c != 0x09 && c != 0x0a && c != 0x0c && c != 0x0d && c != 0x20) {
                break;
            }
            index++;
        }
        if (index == s.length())
            return emptyStringArray;
        ArrayList<String> strings = null;
        int lastIndex = index;
        while (index < sLength) {
            char c = s.charAt(index);
            if (c == 0x09 || c == 0x0a || c == 0x0c || c == 0x0d || c == 0x20) {
                if (lastIndex >= 0) {
                    if (strings == null) {
                        strings = new ArrayList<String>();
                    }
                    strings.add(s.substring(lastIndex, index));
                    lastIndex = -1;
                }
            } else {
                if (lastIndex < 0) {
                    lastIndex = index;
                }
            }
            index++;
        }
        if (lastIndex >= 0) {
            if (strings == null)
                return new String[] { s.substring(lastIndex, index) };
            strings.add(s.substring(lastIndex, index));
        }
        return strings.toArray(emptyStringArray);
    }
}

Related

  1. split(String source, String limit, boolean trim, boolean ignoreWhitespace)
  2. splitAndKeepEscapedSpaces(String string, boolean preserveEscapes)
  3. splitBySpace(String p_str)
  4. splitInWhiteSpaces(String string)
  5. splitNamespaceTitle(String fullTitle)
  6. splitOnSpace(final String string)