remove Punctuation from a string - Java java.lang

Java examples for java.lang:String Whitespace

Description

remove Punctuation from a string

Demo Code

//package com.java2s;

import java.util.Arrays;

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

    public final static char DECIMAL_POINT = 0x002E;

    public static String removePunctuation(String value) {
        return removePunctuation(value, null);
    }

    public static String removePunctuation(String value, char exceptions[]) {
        if (value == null) {
            return "";
        }

        if (exceptions != null) {
            // Must not assume we can modify the character array passed into us
            // must make a copy....
            char copy[] = new char[exceptions.length];
            System.arraycopy(exceptions, 0, copy, 0, exceptions.length);
            exceptions = copy;
            Arrays.sort(exceptions);
        }

        boolean exception = false;
        StringBuilder filteredBuffer = new StringBuilder(value.length());

        for (int i = 0; i < value.length(); i++) {
            char testChar = value.charAt(i);

            if (exceptions != null) {
                exception = (Arrays.binarySearch(exceptions, testChar) >= 0);
            }

            if (exception || Character.isLetterOrDigit(testChar)
                    || testChar == DECIMAL_POINT
                    || Character.isWhitespace(testChar)) {
                filteredBuffer.append(testChar);
            }
        }
        return filteredBuffer.toString();
    }

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

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

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

Related Tutorials