Java String Whitespace Normalize normalizeWhitespace(String source)

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

Description

INTERNAL: Replaces sequences of one or more ' ', \t, \n, \r by a single space, returning the new string.

License

Apache License

Declaration

public static String normalizeWhitespace(String source) 

Method Source Code

//package com.java2s;
/*// w ww .  j av a  2s . c o  m
 * #!
 * Ontopia Engine
 * #-
 * Copyright (C) 2001 - 2013 The Ontopia Project
 * #-
 * 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.
 * !#
 */

public class Main {
    /**
     * INTERNAL: Replaces sequences of one or more ' ', \t, \n, \r by a
     * single space, returning the new string.
     */
    public static String normalizeWhitespace(String source) {
        char[] string = source.toCharArray();
        int pos = 0;
        boolean previousWasWS = false;

        for (int ix = 0; ix < string.length; ix++) {
            switch (string[ix]) {
            case ' ':
            case '\t':
            case '\n':
            case '\r':
                previousWasWS = true;
                break;
            default:
                if (previousWasWS) {
                    string[pos++] = ' ';
                    previousWasWS = false;
                }
                string[pos++] = string[ix];
            }
        }

        if (previousWasWS)
            string[pos++] = ' ';

        return new String(string, 0, pos);
    }
}

Related

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