Java Stack Usage split(final String str)

Here you can find the source of split(final String str)

Description

Splits the provided text into an array, using whitespace as the separator.

License

Open Source License

Parameter

Parameter Description
str the String to parse, may be null.

Return

an array of parsed Strings, null if null String input

Declaration

public static String[] split(final String str) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 MadRobot.//from  w  w w .jav  a  2s .  c  o m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/

import java.util.ArrayList;

public class Main {
    /**
     * Space character.
     */
    private final static char SPACE = 32;

    /**
     * Splits the provided text into an array, using whitespace as the
     * separator.
     * 
     * @param str
     *            the String to parse, may be null.
     * @return an array of parsed Strings, null if null String input
     */
    public static String[] split(final String str) {
        return split(str, null, -1);
    }

    /**
     * Split a string into an array of string
     * 
     * @param toSplit
     *            string to split
     * @param delimiter
     *            character
     * @param ignoreEmpty
     *            flag to ignore empty spaces
     * @return array of string that is split at the given delimiter
     */
    public static String[] split(String toSplit, char delimiter, boolean ignoreEmpty) {
        StringBuilder buffer = new StringBuilder();
        java.util.Stack<String> stringStack = new java.util.Stack<String>();
        try {
            for (int i = 0; i < toSplit.length(); i++) {
                if (toSplit.charAt(i) != delimiter) {

                    buffer.append(toSplit.charAt(i));
                } else {
                    if ((buffer.toString().trim().length() == 0) && ignoreEmpty) {

                    } else {
                        stringStack.addElement(buffer.toString());
                    }
                    buffer = new StringBuilder();
                }
            }
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("[StringUtil.split] " + e.toString());
        }
        if (buffer.length() != 0) {
            stringStack.addElement(buffer.toString());
        }

        String[] split = new String[stringStack.size()];
        for (int i = 0; i < split.length; i++) {
            split[split.length - 1 - i] = stringStack.pop();
        }
        stringStack = null;
        buffer = null;
        return split;
    }

    /**
     * Splits the provided text into an array with a maximum length, separators
     * specified.
     * 
     * @param str
     *            the String to parse, may be null.
     * @param separatorChars
     *            the characters used as the delimiters, null splits on
     *            whitespace
     * @param max
     *            the maximum number of elements to include in the array. A zero
     *            or negative value implies no limit
     * 
     * @return an array of parsed Strings, null if null String input.
     */
    public static String[] split(final String str, final String separatorChars, final int max) {
        return splitWorker(str, separatorChars, max, false);
    }

    /**
     * Gets a CharSequence length or <code>0</code> if the CharSequence is
     * <code>null</code>.
     * 
     * @param cs
     *            a CharSequence or <code>null</code>
     * @return CharSequence length or <code>0</code> if the CharSequence is
     *         <code>null</code>.
     */
    public static int length(CharSequence cs) {
        return cs == null ? 0 : cs.length();
    }

    private static String[] splitWorker(final String str, final String separatorChars, final int max,
            final boolean preserveAllTokens) {

        String[] result = null;

        if ((str != null) && (str.length() == 0)) {
            result = new String[0];
        } else if (str != null) {
            int len = str.length();
            ArrayList<String> list = new ArrayList<String>();
            int sizePlus1 = 1;
            int i = 0, start = 0;
            boolean match = false;
            boolean lastMatch = false;
            if (separatorChars == null) {
                // Null separator means use whitespace
                while (i < len) {
                    if (SPACE == str.charAt(i)) {
                        if (match || preserveAllTokens) {
                            lastMatch = true;
                            if (sizePlus1++ == max) {
                                i = len;
                                lastMatch = false;
                            }
                            list.add(str.substring(start, i));
                            match = false;
                        }
                        start = ++i;
                        continue;
                    }
                    lastMatch = false;
                    match = true;
                    i++;
                }
            } else if (separatorChars.length() == 1) {
                // Optimise 1 character case
                char sep = separatorChars.charAt(0);
                while (i < len) {
                    if (str.charAt(i) == sep) {
                        if (match || preserveAllTokens) {
                            lastMatch = true;
                            if (sizePlus1++ == max) {
                                i = len;
                                lastMatch = false;
                            }
                            list.add(str.substring(start, i));
                            match = false;
                        }
                        start = ++i;
                        continue;
                    }
                    lastMatch = false;
                    match = true;
                    i++;
                }
            } else {
                // standard case
                while (i < len) {
                    if (separatorChars.indexOf(str.charAt(i)) >= 0) {
                        if (match || preserveAllTokens) {
                            lastMatch = true;
                            if (sizePlus1++ == max) {
                                i = len;
                                lastMatch = false;
                            }
                            list.add(str.substring(start, i));
                            match = false;
                        }
                        start = ++i;
                        continue;
                    }
                    lastMatch = false;
                    match = true;
                    i++;
                }
            }
            if (match || (preserveAllTokens && lastMatch)) {
                list.add(str.substring(start, i));
            }

            result = new String[list.size()];
            for (int j = 0; j < list.size(); j++) {
                result[j] = list.get(j);
            }
        }
        return result;

    }

    /**
     * <p>
     * Finds the first index within a String from a start position, handling
     * <code>null</code>. This method uses {@link String#indexOf(int, int)}.
     * </p>
     * 
     * <p>
     * A <code>null</code> or empty ("") String will return
     * <code>(INDEX_NOT_FOUND) -1</code>. A negative start position is treated
     * as zero. A start position greater than the string length returns
     * <code>-1</code>.
     * </p>
     * 
     * <pre>
     * StringUtils.indexOf(null, *, *)          = -1
     * StringUtils.indexOf("", *, *)            = -1
     * StringUtils.indexOf("aabaabaa", 'b', 0)  = 2
     * StringUtils.indexOf("aabaabaa", 'b', 3)  = 5
     * StringUtils.indexOf("aabaabaa", 'b', 9)  = -1
     * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
     * </pre>
     * 
     * @param str
     *            the String to check, may be null
     * @param searchChar
     *            the character to find
     * @param startPos
     *            the start position, negative treated as zero
     * @return the first index of the search character, -1 if no match or
     *         <code>null</code> string input
     */
    public static int indexOf(String str, int searchChar, int startPos) {
        if (isBlank(str)) {
            return -1;
        }
        return str.indexOf(searchChar, startPos);
    }

    /**
     * <p>
     * Finds the first index within a String, handling <code>null</code>. This
     * method uses {@link String#indexOf(String, int)}.
     * </p>
     * 
     * <p>
     * A <code>null</code> String will return <code>-1</code>. A negative start
     * position is treated as zero. An empty ("") search String always matches.
     * A start position greater than the string length only matches an empty
     * search String.
     * </p>
     * 
     * <pre>
     * StringUtils.indexOf(null, *, *)          = -1
     * StringUtils.indexOf(*, null, *)          = -1
     * StringUtils.indexOf("", "", 0)           = 0
     * StringUtils.indexOf("", *, 0)            = -1 (except when * = "")
     * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
     * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
     * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
     * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
     * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
     * StringUtils.indexOf("aabaabaa", "b", -1) = 2
     * StringUtils.indexOf("aabaabaa", "", 2)   = 2
     * StringUtils.indexOf("abc", "", 9)        = 3
     * </pre>
     * 
     * @param str
     *            the String to check, may be null
     * @param searchStr
     *            the String to find, may be null
     * @param startPos
     *            the start position, negative treated as zero
     * @return the first index of the search String, -1 if no match or
     *         <code>null</code> string input
     */
    public static int indexOf(String str, String searchStr, int startPos) {
        if (str == null || searchStr == null) {
            return -1;
        }
        return str.indexOf(searchStr, startPos);
    }

    /**
     * <p>
     * Checks if a CharSequence is whitespace, empty ("") or null.
     * </p>
     * 
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     * 
     * @param cs
     *            the CharSequence to check, may be null
     * @return <code>true</code> if the CharSequence is null, empty or
     *         whitespace
     */
    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(cs.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. removeBackets(String cont)
  2. removeDotSegments(String relativePath)
  3. removeParenthesis(String text)
  4. resolveOneLineExpression(String line, String space, List target)
  5. resolveSeparateIfSentence(List lines, int cursor, List target, String space)
  6. split(String string, String token)