Java String Split by Delimiter splitAndTrim(String string, String delim)

Here you can find the source of splitAndTrim(String string, String delim)

Description

Like org.mule.util.StringUtils#split(String,String) , but additionally trims whitespace from the result tokens.

License

Open Source License

Declaration

public static String[] splitAndTrim(String string, String delim) 

Method Source Code


//package com.java2s;
/*/*from  ww w .  j  av  a  2  s .c  o  m*/
 * $Id$
 * -------------------------------------------------------------------------------------
 * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Like {@link org.mule.util.StringUtils#split(String, String)}, but
     * additionally trims whitespace from the result tokens.
     */
    public static String[] splitAndTrim(String string, String delim) {
        if (string == null) {
            return null;
        }

        if (isEmpty(string)) {
            return new String[] {};
        }

        String[] rawTokens = string.split(delim);
        List<String> tokens = new ArrayList<String>();
        String token;
        if (rawTokens != null) {
            for (int i = 0; i < rawTokens.length; i++) {
                token = rawTokens[i];
                if (token != null && token.length() > 0) {
                    tokens.add(token.trim());
                }
            }
        }
        return tokens.toArray(new String[tokens.size()]);
    }

    /**
     * <p>Checks if a String is empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * </pre>
     *
     * <p>NOTE: This method changed in Lang version 2.0.
     * It no longer trims the String.
     * That functionality is available in isBlank().</p>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if the String is empty or null
     */
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}

Related

  1. split(String value, String[] delimiters)
  2. split(String what, char delim)
  3. split(String[] srcArray, String delimiterRegExp)
  4. split2(String string, String delimiter)
  5. splitAll(String str, String delim)
  6. SplitAt(String s, String delimiter)
  7. SplitAt(String str, String delimiter)
  8. splitByStr(String s, String delim)
  9. splitChars(String str, String delimiters)