Java String Chomp chomp(String s)

Here you can find the source of chomp(String s)

Description

Removes the line-break from the end of the string.

License

Apache License

Declaration

public static String chomp(String s) 

Method Source Code

//package com.java2s;
/*//w  w w . j ava 2 s  . c  om
 * Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky
 * 
 * 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 {
    /**
     * Removes the line-break from the end of the string. 
     */
    public static String chomp(String s) {
        if (s.endsWith("\r\n")) {
            return s.substring(0, s.length() - 2);
        }
        if (s.endsWith("\r") || s.endsWith("\n")) {
            return s.substring(0, s.length() - 1);
        }
        return s;
    }

    /**
     * Removes the line-break from the end of the {@link StringBuffer}. 
     */
    public static void chomp(StringBuffer sb) {
        int ln = sb.length();
        if (ln >= 2 && sb.charAt(ln - 2) == '\r' && sb.charAt(ln - 1) == '\n') {
            sb.setLength(ln - 2);
        } else if (ln >= 1) {
            char c = sb.charAt(ln - 1);
            if (c == '\n' || c == '\r') {
                sb.setLength(ln - 1);
            }
        }
    }
}

Related

  1. chomp(final String s, final String suffix)
  2. chomp(String in)
  3. chomp(String inStr)
  4. chomp(String options)
  5. chomp(String path)
  6. chomp(String s)
  7. chomp(String sd, String c)
  8. chomp(String str)
  9. chomp(String str)