Here you can find the source of getRandomString(Random random, int totalLength, int randomSectionLength)
Parameter | Description |
---|---|
totalLength | - the total length of the string. |
randomSectionLength | - the length of the random section of the string. If randomSectionLength is smaller than totalLength, the final string consists in identical repeated sections; the section that will be repeated is 'randomSectionLength' long and it is randomly generated. |
public static String getRandomString(Random random, int totalLength, int randomSectionLength)
//package com.java2s; /*/*from ww w . ja v a2s . c om*/ * Copyright (c) 2015 Nova Ordis LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Random; public class Main { /** * Naive implementation - come up with something smarter. * * @param totalLength - the total length of the string. * @param randomSectionLength - the length of the random section of the string. If randomSectionLength * is smaller than totalLength, the final string consists in identical repeated sections; the section that * will be repeated is 'randomSectionLength' long and it is randomly generated. */ public static String getRandomString(Random random, int totalLength, int randomSectionLength) { String randomSection = ""; int r; if (totalLength < randomSectionLength) { randomSectionLength = totalLength; } if (randomSectionLength <= 0) { throw new IllegalArgumentException("invalid length " + randomSectionLength); } for (int i = 0; i < randomSectionLength; i++) { r = random.nextInt(122); if (r >= 0 && r <= 25) { r += 65; } else if (r >= 26 && r <= 47) { r += 71; } else if (r >= 58 && r <= 64) { r += 10; } else if (r >= 91 && r <= 96) { r += 10; } // else if ((r >=48 && r <=57) || (r >=65 && r <=90) || (r >=97 && r <=122)) // { // // nothing, we're good // } randomSection += ((char) r); } if (totalLength == randomSectionLength) { return randomSection; } else if (totalLength > randomSectionLength) { char[] src = randomSection.toCharArray(); int sections = totalLength / randomSectionLength; char[] buffer = new char[totalLength]; for (int i = 0; i < sections; i++) { System.arraycopy(src, 0, buffer, i * randomSectionLength, randomSectionLength); } int rest = totalLength - sections * randomSectionLength; System.arraycopy(src, 0, buffer, sections * randomSectionLength, rest); return new String(buffer); } throw new RuntimeException("NOT YET IMPLEMENTED"); } }