Search In This Blog

2016-09-17

How to get random strings by Apex?

This post will introduce how to make a random string for using as a token or as a special code.

First, make sure what string you want to get. If you just want a random string within all number, use Math.random() and do for loop will be a easy way. But if you want to pick up the chars or numbers from a special list, try below.

// the list that you want to pick chars and numbers from
String CharList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';

// position in list, count will start from 0. EX. 'a' is in position 0, 'b' is in position 1
Integer position;

// length of random strings, ex. 20
Integer LengthRequired = '20';

// get 20 chars from list randomly
for(Integer i = 0; i <= LengthRequired; i++) {

    position = Integer.valueof(String.valueof(Math.roundToLong(CharList.length()*Math.random()))) -1;

    // the random Strings
    String Res += CharList.substring(position,position+1);

}

No comments:

Post a Comment