Create an all lowercase version substituting "_" for non-alphanumeric with trailing "_". - Java java.lang

Java examples for java.lang:String Case

Description

Create an all lowercase version substituting "_" for non-alphanumeric with trailing "_".

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "java2s.com";
        int max = 4;
        int min = 2;
        System.out.println(simplifyString(s, max, min));
    }/*from www  .j  av a 2  s .  c om*/

    /**
     * Create an all lowercase version substituting "_" for non-alphanumeric with
     * trailing "_".  Limits the length.
     *
     * @param s the String
     * @param max the max number of characters to be output
     * @param min the min number of characters to be outpu
     *
     * @return
     */
    public static String simplifyString(String s, int max, int min) {
        s = "" + s;
        if (min > max) {
            min = max;
        }

        // normalize to lowercase
        s = s.toLowerCase();

        // hold in a StringBuilder
        StringBuilder sb = new StringBuilder();

        // replace any non alphanumeric chars with underscore
        for (int i = 0; (i < s.length()) && (i < max); i++) {
            char c = s.charAt(i);
            if (((c > ('a' - 1)) && (c < ('z' + 1)))
                    || ((c > ('0' - 1)) && (c < ('9' + 1)))) {
                sb.append(c);
            } else {
                sb.append('_');
            }
        }

        sb.append('_');

        // fill out to minimum length with underscores
        while (sb.length() < min) {
            sb.append('_');
        }

        // return the StringBuilder as a String.
        return sb.toString();
    }
}

Related Tutorials