Java Line Ending standardizeLineEndings(String data)

Here you can find the source of standardizeLineEndings(String data)

Description

Convert text from other line ending formats into our internal format.

License

Open Source License

Parameter

Parameter Description
data The text to convert.

Return

The converted text.

Declaration

public static final String standardizeLineEndings(String data) 

Method Source Code

//package com.java2s;
/*/*ww  w  .ja  v  a 2 s  .  co  m*/
 * Copyright (c) 1998-2015 by Richard A. Wilkes. All rights reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * version 2.0. If a copy of the MPL was not distributed with this file, You
 * can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This Source Code Form is "Incompatible With Secondary Licenses", as defined
 * by the Mozilla Public License, version 2.0.
 */

public class Main {
    private static final String NEWLINE = "\n";

    /**
     * Convert text from other line ending formats into our internal format.
     *
     * @param data The text to convert.
     * @return The converted text.
     */
    public static final String standardizeLineEndings(String data) {
        return standardizeLineEndings(data, NEWLINE);
    }

    /**
     * Convert text from other line ending formats into a specific format.
     *
     * @param data The text to convert.
     * @param lineEnding The desired line ending.
     * @return The converted text.
     */
    public static final String standardizeLineEndings(String data, String lineEnding) {
        int length = data.length();
        StringBuilder buffer = new StringBuilder(length);
        char ignoreCh = 0;

        for (int i = 0; i < length; i++) {
            char ch = data.charAt(i);

            if (ch == ignoreCh) {
                ignoreCh = 0;
            } else if (ch == '\r') {
                ignoreCh = '\n';
                buffer.append(lineEnding);
            } else if (ch == '\n') {
                ignoreCh = '\r';
                buffer.append(lineEnding);
            } else {
                ignoreCh = 0;
                buffer.append(ch);
            }
        }

        return buffer.toString();
    }
}

Related

  1. standardizeLineEndings(String string)