Chop a string by character - Java java.lang

Java examples for java.lang:String Trim

Description

Chop a string by character

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(chomp(str));
    }/*from ww w.ja  va 2  s.c  om*/

    public static final String EMPTY_STRING = "";

    public static String chomp(String str) {
        if ((str == null) || (str.length() == 0)) {
            return str;
        }

        if (str.length() == 1) {
            char ch = str.charAt(0);

            if ((ch == '\r') || (ch == '\n')) {
                return EMPTY_STRING;
            } else {
                return str;
            }
        }

        int lastIdx = str.length() - 1;
        char last = str.charAt(lastIdx);

        if (last == '\n') {
            if (str.charAt(lastIdx - 1) == '\r') {
                lastIdx--;
            }
        } else if (last == '\r') {
        } else {
            lastIdx++;
        }

        return str.substring(0, lastIdx);
    }

    public static String chomp(String str, String separator) {
        if ((str == null) || (str.length() == 0) || (separator == null)) {
            return str;
        }

        if (str.endsWith(separator)) {
            return str.substring(0, str.length() - separator.length());
        }

        return str;
    }

}

Related Tutorials