Reputation: 1362
I would like to know if there is a way to get a random letter (from A-Z)
Thanks for any help.
Upvotes: 4
Views: 11242
Reputation: 2150
Roger Baretto's answer fixed with Cem's hint ))
Function RandomString(iSize)
Const VALID_TEXT = "abcdefghijklmnopqrstuvwxyz1234567890"
Dim Length, sNewSearchTag, I
Length = Len(VALID_TEXT)
Randomize()
For I = 1 To iSize
sNewSearchTag = sNewSearchTag & Mid(VALID_TEXT, Int(Rnd()*Length + 1), 1)
Next
RandomString = sNewSearchTag
End Function
Upvotes: 4
Reputation: 75
Rogerio's answer is fine but Round(Rnd * Len(VALID_TEXT)) can be 0 and Mid cannot start from 0. Fix it if you want to use this function.
Upvotes: 2
Reputation: 2284
I came to a solution that you can have easy control of what are the valid values for your generator.
Function CreateRandomString(iSize)
Const VALID_TEXT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Dim sNewSearchTag
Dim I
For I = 0 To iSize
Randomize
sNewSearchTag = sNewSearchTag & Mid(VALID_TEXT,Round(Rnd * Len(VALID_TEXT)),1)
Next
CreateRandomString = sNewSearchTag
End Function
Upvotes: 3
Reputation: 50835
I think this is what you're looking for. Generate a Random Letter in ASP:
Function RandomNumber(LowNumber, HighNumber)
RANDOMIZE
RandomNumber = Round((HighNumber - LowNumber + 1) * Rnd + LowNumber)
End Function
Assign the function to a variable and pass in the LowNumber (26) and the HighNumber (97) and convert the value returned to the character it represents:
RandomLetter = CHR(RandomNumber(97,122))
You'll want your range to be between 65 and 90 (A and Z) for capital letters.
Upvotes: 6
Reputation: 3772
Here is another way to look at it without using an if/switch.
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Random rand = new Random();
char randomCharacter = alphabet[rand.Next(0, 25)];
Upvotes: 3
Reputation: 2470
use a random number... like this:
Function RandomNumber(LowNumber, HighNumber)
RANDOMIZE
RandomNumber = Round((HighNumber - LowNumber + 1) * Rnd + LowNumber)
End Function
and then use it from 1-26, use "if" or switch, to get the letter.
Upvotes: 2