How to generate sequential alphanumeric string in Java starting with specific string

1.4k views Asked by At

I want to be able to generate sequential alphanumeric strings of a given length 8. Also, I want the string to start with a specific string let's say "ABC00". Just imagine a license plate starts with a specific string and other generated alphanumeric strings. I have tried a number of things I have seen here and not getting the desired results.

This is what I currently have

import java.security.SecureRandom;
import java.util.Random;

public class RandomString {


    static final String AB = "SCV00" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static SecureRandom rnd = new SecureRandom();

    String randomString(int len){
        StringBuilder sb = new StringBuilder(len);
        for(int i = 0; i < len; i++)
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        return sb.toString();
    }

}

I want my output to look like this. When users provide the number of IDs they want I should be able to generate it. Say, user wants 3 IDs. I should have. So, I just read the requirement properly and there is a slight difference.

Lowercase will be eliminated. This is how the format should look like. The starting string is "CLV0".

CLVO 0001
CLV0 0002
CLV0 0003
:
CLV0 0009
CLV0 000A
CLVO 000B
:
CLV0 000Z
CLV0 0010

This is the actual sequence. It's not random. Kindly help with this

2

There are 2 answers

6
Chaosfire On BEST ANSWER

I'll assume you need 0000 to 000Z, then 0010, 0011, 0012 and so on. You would need to keep track of the current id you need to generate. Something like this:

public class SequentialString {

    private static final String START = "CLV0";
    private static final String ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static void main(String[] args) {
        int totalLength = 8;
        int numberOfIds = 111;
        int countRemainingSymbols = totalLength - START.length();
        for (int i = 0; i < numberOfIds; i++) {
            StringBuilder end = new StringBuilder();
            int current = i;//depending on exact case, you would need to keep track of current
            int remainder = current % ALPHANUMERIC.length();//the index of next character
            do {
                end.append(ALPHANUMERIC.charAt(remainder));
                current /= ALPHANUMERIC.length();//update to check if we need to add more characters
                remainder = current % ALPHANUMERIC.length();//update index, only used if more chars are needed
            } while (current > 0);
            int padCount = countRemainingSymbols - end.length();
            StringBuilder result = new StringBuilder(START).append("-");//- is for easier debugging, remove it for your case
            for (int j = 0; j < padCount; j++) {
                result.append("0");
            }
            result.append(end.reverse());
            System.out.println(result);
        }
    }
}

Basically, using current and length of ALPHANUMERIC to calculate next char index, then calculate if more characters are needed, keep looping until no more chars are needed. Note that i am reversing generated sequence(variable end in code) before appending it.

Also note that this solution is not limited to ZZZZ, it can keep generating the sequence even after that.

0
Tim Biegeleisen On

You could leverage UUID here:

String uuid = UUID.randomUUID().toString().replace("-", "");
String randomString = "SCV00" + uuid.substring(0, 5);
System.out.println(randomString);  // SCV00f044d