How do I generate a random string?

  • How does one generate a random string sequence with Apex? I need to generate a code when a particular object is created in our Salesforce environment. I'd like the code to contain numbers from 0-9 and letters from A-Z.

    Searching their rather awful developer forums I found:

    Blob blobKey = crypto.generateAesKey(128);
    String key = EncodingUtil.convertToHex(blobKey);
    return key.substring(0,len);

    However this isn't going to cover a very large range of letters.

    In the C# world something like the following would do the trick:

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    var result = new string(
        Enumerable.Repeat(chars, numberOfCharacters)
                  .Select(s => s[random.Next(s.Length)])

    Is there an easy way to do something similar in Apex that I'm just not familiar with?

  • greenstork

    greenstork Correct answer

    7 years ago

    Here is a static method that accepts a desired string length as an argument. It takes a full string of ASCII numbers and letters and loops through the index of your desired string length, randomly choosing an index in the full character string.

    public static String generateRandomString(Integer len) {
        final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        String randStr = '';
        while (randStr.length() < len) {
           Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
           randStr += chars.substring(idx, idx+1);
        return randStr; 

    I've added a brief explanation.

    Nice, question, how would you test this code? Maybe it would not be required.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM