("Random string of 10 numbers: " + randomString) RandomString = RandomStringUtils.randomNumeric(10) ("Random string of 10 alphabets: " + randomString) String randomString = RandomStringUtils.randomAlphabetic(10) generate a random string of 10 alphabets It has methods that can generate a random string of only alphabets( randomAlphabetic), numbers( randomNumeric) or both( randomAlphanumeric).Īll these methods accept an integer argument which represents the length of the string that they will generate.īelow is an example. Output of three executions of above program isĪpache Commons Lang library has an .RandomStringUtils class with methods to generate random string of a fixed length. You can also use class to generate a random integer. Int randomIndex = random.nextInt(allCharacters.length()) This method follows a similar approach as the above method in that a super set of all the characters is created, a random index is generated and character at that index is used to create the final string.īut this approach uses class to generate a random index. Output of above program executed thrice is RandomString.append(allCharacters.charAt(randomIndex)) retrieve character at index and add it to result Int randomIndex = (int)(Math.random() * allCharacters.length()) generate a random number between 0 and length of all characters StringBuffer randomString = new StringBuffer() String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz" String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |