Java String Whitespace Normalize normalizeWhitespace(String s)

Here you can find the source of normalizeWhitespace(String s)

Description

Removes all leading and trailing whitespace from a string, and replaces all internal whitespace with a single space character.

License

Open Source License

Parameter

Parameter Description
s the string, or <code>null</code>.

Return

the string with all leading and trailing whitespace removed and all internal whitespace normalized, never null.

Declaration

public static String normalizeWhitespace(String s) 

Method Source Code

//package com.java2s;
// See the COPYRIGHT file for copyright and license information

public class Main {
    /**/* w w w .ja  v a2 s  .  c  o m*/
     * Removes all leading and trailing whitespace from a string, and replaces all internal whitespace with a single space character. If <code>null</code> is passed, then <code>""</code> is returned.
     * 
     * @param s
     *            the string, or <code>null</code>.
     * @return the string with all leading and trailing whitespace removed and all internal whitespace normalized, never <code>null</code>.
     */
    public static String normalizeWhitespace(String s) {
        String normalized = "";
        if (s != null) {
            s = s.trim();
            boolean prevIsWhitespace = false;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                boolean thisIsWhitespace = (c <= 0x20);

                if (!(thisIsWhitespace && prevIsWhitespace)) {
                    if (thisIsWhitespace) {
                        normalized += ' ';
                        prevIsWhitespace = true;
                    } else {
                        normalized += c;
                        prevIsWhitespace = false;
                    }
                }
            }
        }
        return normalized;
    }
}

Related

  1. normalizeWhitespace(final String str)
  2. normalizeWhitespace(String dirtyString)
  3. normalizeWhiteSpace(String input)
  4. normalizeWhiteSpace(String input)
  5. normalizeWhitespace(String orig)
  6. normalizeWhitespace(String source)
  7. normalizeWhiteSpace(String src)
  8. normalizeWhitespace(String text)
  9. normalizeWhitespaces(String s)