Tuesday, September 6, 2011

Generate Unique String with only Special Characters.


Following code will generate the unique string containing the special characters. You can specify the length of the string to generate.

 public class UniqueStringGenerator {

    /** 
     * Minimum length for a decent string 
     */  
    public static final int MIN_LENGTH = 5;  
   
    /** 
     * The random number generator. 
     */  
    protected static java.util.Random r = new java.util.Random();  
   
    protected static char[] goodChar = {  
        // Comment out next two lines to make upper-case-only, then  
        // use String toUpper() on the user's input before validating.  
        '~', '`', '@', '#', '$', '%', '^','&','*','(',')','{','}','[', ']',':'
    };  
   
    //Generate a Password object with a random password.  
    public static String getNext() {  
        return getNext(MIN_LENGTH);  
    }  
   
    // Generate a unique string with a random function.  
    public static String getNext(int length) {  
        if (length < 1) {  
            throw new IllegalArgumentException(  
                    "Ridiculous password length " + length);  
        }  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < length; i++) {  
            sb.append(goodChar[r.nextInt(goodChar.length)]);  
        }  
        return sb.toString();  
    }  
    
    public static void main(String[] args) {
        System.out.println(getNext());
    }
 }

No comments:

Post a Comment