Java String Whitespace Delete deleteWhitespace(final String s)

Here you can find the source of deleteWhitespace(final String s)

Description

Deletes all whitespaces from a String as defined by Character#isWhitespace(char) .

Parameter

Parameter Description
s the String to delete whitespace from, may be null

Return

the String without whitespaces, null if null String input

Declaration

public static String deleteWhitespace(final String s) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from  w w w .j av  a2 s  .c o m*/
     * <p>
     * Deletes all whitespaces from a String as defined by
     * {@link Character#isWhitespace(char)}.
     * </p>
     *
     * <pre>
     * StringUtils.deleteWhitespace(null)         = null
     * StringUtils.deleteWhitespace("")           = ""
     * StringUtils.deleteWhitespace("abc")        = "abc"
     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
     * </pre>
     *
     * @param s
     *            the String to delete whitespace from, may be null
     * @return the String without whitespaces, {@code null} if null String input
     */
    public static String deleteWhitespace(final String s) {
        if (isEmpty(s)) {
            return s;
        }
        final int sz = s.length();
        final char[] chs = new char[sz];
        int count = 0;
        for (int i = 0; i < sz; i++) {
            if (!Character.isWhitespace(s.charAt(i))) {
                chs[count++] = s.charAt(i);
            }
        }
        if (count == sz) {
            return s;
        }
        return new String(chs, 0, count);
    }

    /**
     * <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>
     */
    public static boolean isEmpty(final String s) {
        return s == null || s.length() == 0;
    }
}

Related

  1. deleteWhitespace(CharSequence sequence)
  2. deleteWhitespace(CharSequence str)
  3. deleteWhitespace(final String str)
  4. deleteWhitespace(String s)
  5. deleteWhiteSpace(String s)
  6. deleteWhitespace(String str)