Java Array Chomp chomp(char[] charArray)

Here you can find the source of chomp(char[] charArray)

Description

Given a character array, this method constructs a new string without trailing carriage return or newline characters.

License

Apache License

Parameter

Parameter Description
charArray the character array to construct string from

Return

A string without trailing carriage returns or newlines.

Declaration

public static String chomp(char[] charArray) 

Method Source Code

//package com.java2s;
/**/*from   ww w. j av  a 2  s.  c o  m*/
 * Copyright (C) 2012 Red Hat, Inc. and/or its affiliates.
 *
 * 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 {
    /**
     * Given a character array, this method constructs a new string without
     * trailing carriage return or newline characters.
     *
     * @param charArray the character array to construct string from
     * @return A string without trailing carriage returns or newlines.
     */
    public static String chomp(char[] charArray) {
        // length of String to return
        int length = charArray.length;

        // index of last char in buffer
        int endIndex = charArray.length - 1;

        // From end of char buffer...
        for (int i = endIndex; i > -1; i--) {
            // ...identify carriage return or newline...
            if (charArray[i] == '\r' || charArray[i] == '\n') {
                // ...decrement length of String to return
                length--;
            } else {
                // ...or exit loop
                break;
            }
        }

        return new String(charArray, 0, length);
    }
}

Related

  1. chompArray(char[] array, int start, int end)