Trim the elements of the given String array, calling String.trim() on each of them. - Java java.lang

Java examples for java.lang:String Strip

Description

Trim the elements of the given String array, calling String.trim() on each of them.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(java.util.Arrays
                .toString(trimArrayElements(array)));
    }//from   w w w.  j  a  v a  2s  .  co m

    /**
     * Trim the elements of the given String array, calling <code>String.trim()</code> on each of them.
     *
     * @param array
     *            the original String array
     * @return the resulting array (of the same size) with trimmed elements
     */
    public static String[] trimArrayElements(final String[] array) {

        // if (ObjectUtils.isEmpty(array)) {
        if (array.length == 0)
            return new String[0];
        final String[] result = new String[array.length];
        for (int i = 0; i < array.length; i++) {
            final String element = array[i];
            result[i] = (element != null ? element.trim() : null);
        }
        return result;
    }
}

Related Tutorials