Java String Chop chop(String str)

Here you can find the source of chop(String str)

Description

Remove the last character from a String.

License

Open Source License

Parameter

Parameter Description
str String to chop last character from

Exception

Parameter Description
NullPointerException if str is <code>null</code>

Return

String without last character

Declaration

public static String chop(String str) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from  w  w  w. jav  a  2s  .c  om
     * <p>
     * Remove the last character from a String.
     * </p>
     * 
     * <p>
     * If the String ends in <code>\r\n</code>, then remove both of them.
     * </p>
     * 
     * @param str
     *            String to chop last character from
     * @return String without last character
     * @throws NullPointerException
     *             if str is <code>null</code>
     */
    public static String chop(String str) {
        if ("".equals(str)) {
            return "";
        }
        if (str.length() == 1) {
            return "";
        }
        int lastIdx = str.length() - 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

  1. chop(String s)
  2. chop(String s, int i)
  3. chop(String s, int maxLength)
  4. chop(String src, String delim)
  5. chop(String str)
  6. chop(String str)
  7. chop(String str)
  8. chop(String str)
  9. chop(String str)