Removes leading and trailing whitespaces from s and replaces all sequences of whitespaces inside s with a single space character. - Java java.lang

Java examples for java.lang:String Replace

Description

Removes leading and trailing whitespaces from s and replaces all sequences of whitespaces inside s with a single space character.

Demo Code

/*//  www. j a v a2s  . c  o m
 * Copyright 2009-2012 Michael Tamm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "java2s.com";
        System.out.println(normalizeSpace(s));
    }

    /**
     * Removes leading and trailing whitespaces from <code>s</code> and replaces
     * all sequences of whitespaces inside <code>s</code> with a single space character.
     */
    public static String normalizeSpace(String s) {
        final String result;
        if (s == null) {
            result = null;
        } else {
            final int n = s.length();
            final StringBuilder sb = new StringBuilder(n);
            boolean lastCharacterWasWhitespace = true;
            for (int i = 0; i < n; ++i) {
                final char c = s.charAt(i);
                if (Character.isWhitespace(c)) {
                    lastCharacterWasWhitespace = true;
                } else {
                    if (lastCharacterWasWhitespace && sb.length() > 0) {
                        sb.append(' ');
                    }
                    sb.append(c);
                    lastCharacterWasWhitespace = false;
                }
            }
            result = sb.toString();
        }
        return result;
    }
}

Related Tutorials