Write code to chop ending new line character from a string - Java java.lang

Java examples for java.lang:String Trim

Requirements

Write code to chop

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(chop(str));
    }//w ww.  j av  a  2s  .co m

    public static final String EMPTY_STRING = "";

    public static String chop(String str) {
        if (str == null) {
            return null;
        }

        int strLen = str.length();

        if (strLen < 2) {
            return EMPTY_STRING;
        }

        int lastIdx = strLen - 1;
        String ret = str.substring(0, lastIdx);
        char last = str.charAt(lastIdx);

        if (last == '\n') {
            if (ret.charAt(lastIdx - 1) == '\r') {
                return ret.substring(0, lastIdx - 1);
            }
        }

        return ret;
    }

}

Related Tutorials