I want to make a random character generator with numbers in vb.net, I know how to make a random number generator but not numbers mixed with letters. I want it to be around 15-20 characters.
Something like this:
F53Gsfdsj637jfsj5kd8
Thanks ahead!
You're mostly there once you have a random number generator. From there, just pick a random character within a collection of valid characters. The simplest way would be something like:
dim validchars as string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
dim sb as new StringBuilder()
dim rand as new Random()
for i as Integer = 1 to 10
dim idx as Integer = rand.Next(0, validchars.Length)
dim randomChar as char = validchars(idx)
sb.Append(randomChar)
next i
dim randomString = sb.ToString()
Of course, clean up the syntax a bit, and maybe use a constant value for the chars and length, a variable value for the number of digits, etc.
Related
I want my application to populate random sets of numbers using a list of specific numbers that i chose. For example; I have a set of numbers (1,3,5,9,21,70,56). I want to be able to randomize the order in which these numbers are selected. Is that possible?
If you want to generate a list of 1000 numbers using only those you gave:
Dim r as New Random()
Dim thousand as New List(Of Integer)(1000)
'short way to create an array
Dim onlyFrom = {1,3,5,9,21,70,56}
For i = 1 to 1000
thousand.Add(onlyFrom(r.Next(0, onlyFrom.Length)))
Next i
It repeatedly asks a Random for a random integer between 0 and the array length. Next() may return the lower number, but never the upper number. Documentation
If you want to shuffle those numbers you gave into a random order, easy way to use LINQ:
Dim r as New Random()
Dim onlyFrom = {1,3,5,9,21,70,56}
Dim shuffled = onlyFrom.OrderBy(Function(x) r.Next()).ToArray()
Note: Do not use New Random() in a loop
Randomize()
Dim NumberList= {1,3,5,9,21,70,56}
' Generate random value between 1 and 7, or use NumberList length to make it generic
Dim value As Integer = CInt(Int(( 7 * Rnd()) + 1))
return NumberList(value-1)
* The above code may produce the same value multiple times in a series. so if the requirement is that a different value be produced from the array each time when the code is called seven times, this wouldn't work *
If the requirement is to have a different value from the array each time for the first 7 calls, you may use Shuffle function as laid out here Shuffling an array of strings in vb.net
What is the best appraoch to generate unquie ID's (no special characters) that will be 25 characters in length? I was thinking of generating a GUID and taking a substring of that, but I dont know if thats the best idea for uniqueness.
This is for dissconnected systems use. Creating a primary key in a database will not work in my situation. I need to create a unquie ID manually
I tried this but I am seeing duplicates in the output for some reason. So it doesnt seem too unquie even in this simple test..
Sub Main()
Dim sb As StringBuilder = New StringBuilder
For i As Integer = 1 To 100000
Dim s As String = GenerateRandomString(25, True)
sb.AppendLine(s)
sb.AppendLine(Environment.NewLine)
Next
Console.WriteLine(sb.ToString)
Console.ReadLine()
End Sub
Public Function GenerateRandomString(ByRef len As Integer, ByRef upper As Boolean) As String
Dim rand As New Random()
Dim allowableChars() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim final As String = String.Empty
For i As Integer = 0 To len - 1
final += allowableChars(rand.Next(allowableChars.Length - 1))
Next
Return IIf(upper, final.ToUpper(), final)
End Function
You’re probably seeing duplicates because New Random() is seeded according to a system clock, which may not have changed by the next iteration.
Try a cryptographically secure RNG:
Const ALLOWABLE_ALL As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Const ALLOWABLE_UPPERCASE As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim allowable As String = If(upper, ALLOWABLE_UPPERCASE, ALLOWABLE_ALL)
Dim result(len - 1) As Char
Dim current As Integer = 0
Using r As New Security.Cryptography.RNGCryptoServiceProvider()
Do
Dim buffer(255) As Byte
r.GetBytes(buffer)
For b As Byte In buffer
If b < allowable.Length Then
result(current) = allowable(b)
current += 1
If current = len Then Return New String(result)
End If
Next
Loop
End Using
This is also “more random” than your implementation in that letters aren’t weighted twice as heavily if upper is True.
A GUID might be 32 digits, but only if expressed in hexadecimal. That means it will only use characters 0-9 and A-F. If your string can use the entire alphabet then you can express the same GUID in fewer characters, especially if your string can be case sensitive.
See http://en.wikipedia.org/wiki/Globally_unique_identifier#Text_encoding for an example of alternative encoding, or http://web.archive.org/web/20100408172352/http://prettycode.org/2009/11/12/short-guid/ for example code. EDIT: Or Hans's method above which is much better. If you want to encode a GUID with only A-Z, a-z and 0-9 characters then you will need to look up Base-62 encoding (as opposed to base-64) because you only have 62 characters to encode into.
Stop trying to re-invent the wheel and just use .NET's built in GUID generator:
System.Guid.NewGuid()
which will generate a properly randomly seeded GUID, then simply sub-string it to your limit. Even better if you grab the last 25 chars, instead of the first 25.
PS: I don't consider this a great idea in general, because it's the entire GUID that's considered unique, not part of it, but it should satisfy what you want.
I have an AD username called "lastname-132" in Textbox1, this string is 12 long, so i want to add the username in to Textbox2, but shortened, in the textbox2 i only have a string length of only 10 available due to other tools this program is using, so i don't want to convert it all the time manually and want to just convert it automatically with a onleave event.
Anyone any idea how to write this?
So the End Result should look like this.
'String length can be 20 max.
Textbox1.Text = "lastname-123"
'some code to convert it to this:
'String length 10 max. Numbers and the "-" should stay the same, but remove letters if necessary.
Textbox2.Text = "lastna-123"
Here's the concept:
Split string based on '-' into 2 strings
In the example above: 'lastname' and '123'.
Check the length of the first string and cut if it is too long
the program checks 'lastname' and finds that it is too long, then
cuts it into 'lastna'
Combine 'lastna' and '123' back into a string
I hope this helps
Without more information, this will assume that there can be multiple hyphens, the number can be of variable length, and you can change the maximum length of the string by changing one variable.
Dim username As String = "lastname-123"
Dim max As Integer = 10
Dim lindex As Integer = username.LastIndexOf("-")
Dim numberLength As Integer = username.Length - lindex
Dim number As String = username.Substring(lindex)
Dim justName As String = username.Substring(0, lindex)
If justName.Length + numberLength >= max Then
username = justName.Substring(0, max - numberLength) & number
End If
If you are concentrating only on the restriction of length of characters to be accepted then you can use
Maxlength
property of the Textbox.
Ex: Maxlength="10"
restricts the Textbox to accept only 10 characters.
Try to make it fit with for example substring manipulation. See http://msdn.microsoft.com/en-us/library/dd789093.aspx for more info.
I am a newbie to programming and need some help with the basics.
I have a function which takes in an integer value. I want to be able to grab the first digit (or the first and second digits in some cases) of this integer and do something with it.
What is the best way in VB.NET to get the first digit of an integer (or the first and second)?
firstDigit = number.ToString().Substring(0,1)
firstTwoDigits = number.ToString().Substring(0,2);
int.Parse(firstDigit)
int.Parse(firstTwoDigits)
and so forth
I'm not well versed in VB syntax, so forgive me for the syntax errors:
dim i as integer
while i >= 10
i = i \ 10
end while
msgbox "i = " & i
Note, this prints the "first from the left" digit. Like, for "12345" it would print "1".
If you need the digits starting from the end of the integer, just get the modulu result for the tens or the hundreds, according to how many digits you need.
Dim n As Integer
n Mod 10
for the first digit, or:
n Mod 100
for the second and first digits.
If you need the first and second digits from the beginning of the number, there is another answer here which will probably help you.
for first digit you can use:
Dim number As Integer = 234734
Dim first = number.ToString.ToCharArray()(0)
for second digit you can use:
Dim number As Integer = 234734
Dim second = number.ToString.ToCharArray()(1)
This would work. You can use Math.ABS, absolute value, to eliminate negative. The number from left could be replaced by a function if you are using logic, like the overall length of the number, to determine how many of the leading characters you are going to use.
Dim number As Integer = -107
Dim result As String
Dim numberFromLeft As Integer = 2
result = Math.Abs(number).ToString.Substring(0, numberFromLeft)
This results in 10 it is a string but converting it back to a number is easy if you need to. If you need to keep track if it was positive or negative you could use the original value to apply that back to you parsed string.
I have an array of integers like these;
dim x as integer()={10,9,4,7,6,8,3}.
Now I want to pick a random number from it,how can I do this in visual basic?Thanks in advance...
First you need a random generator:
Dim rnd As New Random()
Then you pick a random number that represents an index into the array:
Dim index As Integer = rnd.Next(0, x.Length)
Then you get the value from the array:
Dim value As Integer = x(index)
Or the two last as a single statement:
Dim value As Integer = x(rnd.Next(0, x.Length))
Now, if you also want to remove the number that you picked from the array, you shouldn't use an array in the first place. You should use a List(Of Integer) as that is designed to be dynamic in size.
randomly choose an index from 0 to length-1 from your array.