2017-07-06 169 views

回答

22

是,使用下面的代碼:

import static org.apache.commons.text.CharacterPredicates.DIGITS; 
import static org.apache.commons.text.CharacterPredicates.LETTERS; 

// ... 

RandomStringGenerator generator = new RandomStringGenerator.Builder() 
     .withinRange('0', 'z') 
     .filteredBy(LETTERS, DIGITS) 
     .build(); 
+0

'LETTERS'和'DIGITS'從哪裏來?它們是常量嗎? –

+1

'import static org.apache.commons.text.CharacterPredicates.DIGITS; import static org.apache.commons.text.CharacterPredicates.LETTERS;'。我更新了答案。 –

+1

爲什麼不切斷中間人,並使用'.filteredBy(Character :: isLetter,Character :: isDigit)'? – toKrause

4

我用這個:

static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's', 
     'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A', 
     'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' }; 

private static String randomString(int length) { 
    StringBuilder stringBuilder = new StringBuilder(); 

    for (int i = 0; i < length; i++) { 
     stringBuilder.append(chars[new Random().nextInt(chars.length)]); 
    } 
    return stringBuilder.toString(); 
} 

private static String randomString(int length) { 
    StringBuilder stringBuilder = new StringBuilder(); 

    for (int i = 0; i < length; i++) { 
     switch (new Random().nextInt(3)) { 
      case 0: 
       stringBuilder.append((char) (new Random().nextInt(9) + 48)); 
       break; 
      case 1: 
       stringBuilder.append((char) (new Random().nextInt(25) + 65)); 
       break; 
      case 2: 
       stringBuilder.append((char) (new Random().nextInt(25) + 97)); 
       break; 
      default: 
       break; 
     } 
    } 
    return stringBuilder.toString(); 
} 

enter code here 
+0

這還包括以下字符::; <=>?@ [\]^_' –

+0

@DavidRiccitelli是的,但現在正確。 – mate0406

0

與Java 8 Lambda表達式:

private final RandomStringGenerator generator = new RandomStringGenerator.Builder() 
      .usingRandom(max -> RandomUtils.getRandomAlphanumericChar()).build(); 

.................... 

public class RandomUtils { 

    private final static char[] ALPHA_NUMERIC_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 
      'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
      'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', 
      '5', '6', '7', '8', '9'}; 

    private final static Random random = new SecureRandom(); 

    public static char getRandomAlphanumericChar() { 
     return ALPHA_NUMERIC_CHARS[random.nextInt(ALPHA_NUMERIC_CHARS.length)]; 
    } 
}