function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nick D'AddarioNick D'Addario 

Generate Unique Non-Random String?

Hi All, 

I'm looking to generate a unique string for each account. The string will be a concatenation of the first four letters of the account name and then a couple other characters depending on the natrure of the account. The trouble I'm having is with the unique part. If a generated code matches an existing code, then I'd use the next character in the account name. If there is no next character, use a 1. If there is already a match with the appended 1, use 2 and so on. 

Also, for some context, the code would be generated when a new opportunity is created. 

Anyone have an idea on how I'd accomplish this?

Thanks,
Nick
Raj VakatiRaj Vakati
You can try like this 
 
public static String generateRandomString(String accName , 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 accName+randStr; 
}