trim String from Right - Java java.lang

Java examples for java.lang:String Trim

Description

trim String from Right

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sourceString = "java2s.com";
        System.out.println(trimRight(sourceString));
    }/*from   www . jav a 2  s. co m*/

    public static String trimRight(String sourceString,
            String listOfCharsToRemove) {
        String result = "";
        int length = listOfCharsToRemove.length();

        if (!isEmpty(sourceString)) {
            StringBuilder buffer = new StringBuilder(sourceString);
            boolean done = false;

            while ((buffer.length() > 0) && !done) {
                int offset = buffer.length() - 1;
                done = true;
                for (int i = 0; i < length; i++) {
                    if (buffer.charAt(offset) == listOfCharsToRemove
                            .charAt(i)) {
                        buffer.deleteCharAt(offset);
                        done = false;
                        break;
                    }
                }
            }
            result = buffer.toString();
        }

        return result;
    }

    public static String trimRight(String sourceString) {
        String result = "";

        if (!isEmpty(sourceString)) {
            StringBuilder buffer = new StringBuilder(sourceString);
            int pos = buffer.length() - 1;

            while ((pos >= 0) && Character.isWhitespace(buffer.charAt(pos))) {
                buffer.deleteCharAt(pos--);
            }
            result = buffer.toString();
        }

        return result;
    }

    public static String trimRight(String sourceString, char removeChar) {
        String result = "";

        if (!isEmpty(sourceString)) {
            StringBuilder buffer = new StringBuilder(sourceString);
            int length = buffer.length();

            while ((length > 0) && buffer.charAt(length - 1) == removeChar) {
                buffer.deleteCharAt(length - 1);
                length = buffer.length();
            }

            result = buffer.toString();
        }
        return result;
    }

    public static int length(String source) {
        int result = 0;
        if (isNotEmpty(source)) {
            result = source.length();
        }
        return result;
    }

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

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

Related Tutorials