Java String Split by Delimiter split(String str, String delim)

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

Description

Split the given string str/code> delimited by given delimiter delim into string list.

License

Apache License

Parameter

Parameter Description
str string to split
delim delimiter set which delimit the token in the string, if it's null then use default value : space characters(" \t\r\n\f")

Return

string list contains tokens splitted by given delimiter

Declaration

public static List<String> split(String str, String delim) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**//from ww  w.j  a  v a2  s  .co  m
     * Split the given string <code>str/code> delimited by given delimiter 
     * <code>delim</code> into string list.
     * <p>Examples:
     * <blockquote><pre>
     * StringUtil.split("2005-05-01", "-") return list L[2005,05,01]
     * StringUtil.split("2005 05 01", " ") return list L[2005,05,01]
     * </pre></blockquote>
     * @param str string to split
     * @param delim delimiter set which delimit the token in the string, if it's
     * null then use default value : space characters(" \t\r\n\f")
     * @return string list contains tokens splitted by given delimiter
     */
    public static List<String> split(String str, String delim) {
        List<String> splitList = null;
        StringTokenizer st = null;

        if (str == null) {
            return splitList;
        }

        if (isValid(delim)) {
            st = new StringTokenizer(str, delim);
        } else {
            st = new StringTokenizer(str);
        }

        if ((st != null) && st.hasMoreTokens()) {
            splitList = new ArrayList<String>();

            while (st.hasMoreTokens()) {
                splitList.add(st.nextToken());
            }
        }

        return splitList;
    }

    /**
     * Verify whether the given string <code>str</code> is valid. If the given
     * string is not null and contains any alphabet or digit, then the string
     * is think as valid, otherwise invalid.
     * @param str string to verify
     * @return false if the given string is null or contains only empty character,
     * otherwise return true.
     */
    public static boolean isValid(String str) {
        boolean valid = true;

        if ((str == null) || (str.trim().length() <= 0)) {
            valid = false;
        }

        return valid;
    }
}

Related

  1. split(String str, char delimiter)
  2. split(String str, char delimiter)
  3. split(String str, char delimiter, boolean trim)
  4. split(String str, int delim, String trailing)
  5. split(String str, String delim)
  6. split(String str, String delim)
  7. split(String str, String delim)
  8. split(String str, String delim)
  9. split(String str, String delim)