remove Extra White Space from a string - Java java.lang

Java examples for java.lang:String Whitespace

Description

remove Extra White Space from a string

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String workString = "  java2s.com  ";
        System.out.println(removeExtraWhiteSpace(workString));
    }/*from www  .j av a 2s  .  co  m*/

    public static String removeExtraWhiteSpace(String workString) {

        // handle null or empty strings - nothing to do
        if (isEmpty(workString)) {
            return workString;
        }

        StringBuilder sb = new StringBuilder();

        int wsCount = 0;

        for (int x = 0; x < workString.length(); x++) {
            char ch = workString.charAt(x);

            if (Character.isWhitespace(ch)) {
                if (wsCount == 0) {
                    sb.append(' ');
                }
                wsCount++;
            } else { // non-white, kick it, reset count
                wsCount = 0;
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    public static int length(String source) {
        int result = 0;
        if (isNotEmpty(source)) {
            result = source.length();
        }
        return result;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

Related Tutorials