remove Chars from a string - Java java.lang

Java examples for java.lang:String Trim

Description

remove Chars from a string

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String value = "java2s.com";
        char removeChar = '.';
        System.out.println(removeChars(value, removeChar));
    }//from   w ww . j av  a 2s.c  o  m

    public static String removeChars(String value, char removeChar) {
        return removeChars(value, String.valueOf(removeChar));
    }

    public static String removeChars(String value, String removeChars) {
        String result = "";

        if (!isEmpty(value) && !isEmpty(removeChars)) {

            StringBuilder filteredBuffer = new StringBuilder(value.length());
            for (int i = 0; i < value.length(); i++) {
                if (!contains(removeChars, String.valueOf(value.charAt(i)))) {
                    filteredBuffer.append(value.charAt(i));
                }
            }
            result = filteredBuffer.toString();
        }

        return result;
    }

    public static String removeChars(String source, int offset,
            int numberToRemove) {
        StringBuilder sb = new StringBuilder();
        if (!isEmpty(source)) {
            for (int x = 0; x < source.length(); x++) {
                if (x < offset || x >= (offset + numberToRemove)) {
                    sb.append(source.charAt(x));
                }
            }
        }
        return sb.toString();
    }

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

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

    public static boolean contains(String sourceString, String findString) {
        return (contains(sourceString, findString, true));
    }

    public static boolean contains(String sourceString, char findChar) {
        return (contains(sourceString, String.valueOf(findChar), true));
    }

    public static boolean contains(String sourceString, byte findChar) {
        return (contains(sourceString, String.valueOf(findChar), true));
    }

    public static boolean contains(String sourceString, String findString,
            boolean caseSensitive) {

        if (sourceString == null || findString == null) {
            return false;
        }
        if (!caseSensitive) {
            sourceString = sourceString.toLowerCase();
            findString = findString.toLowerCase();
        }

        return (sourceString.contains(findString));
    }

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

Related Tutorials