Java - Write code to Return a string with non alphanumeric chars converted to the substitute character.

Requirements

Write code to Return a string with non alphanumeric chars converted to the substitute character.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String source = "book2s.com";
        char substitute = 'a';
        System.out.println(toLowerSubset(source, substitute));
    }/*from   w  ww.  j a  v  a  2 s .co m*/

    /**
     * Returns a string with non alphanumeric chars converted to the
     * substitute character. A digit first character is also converted.
     * By sqlbob@users
     * @param source string to convert
     * @param substitute character to use
     * @return converted string
     */
    public static String toLowerSubset(String source, char substitute) {

        int len = source.length();
        StringBuffer sb = new StringBuffer(len);
        char ch;

        for (int i = 0; i < len; i++) {
            ch = source.charAt(i);

            if (!Character.isLetterOrDigit(ch)) {
                sb.append(substitute);
            } else if ((i == 0) && Character.isDigit(ch)) {
                sb.append(substitute);
            } else {
                sb.append(Character.toLowerCase(ch));
            }
        }

        return sb.toString();
    }
}

Related Exercise