473,785 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HOWTO - generate a alphanumeric string of a given length

Is there a function that return some random ID like string alphanumeric?
Like this:
A35sDsd1dSGsH

Thanks
Crirus
Nov 20 '05
10 2621
It would certainly appear that way.
If, rather than a time based seed, you want a randomized seed like OHM's
original example you can update the function as follows.

\\\
Imports System.Security .Cryptography
Imports System.Text

Private Function RandomString(By Val Stringlength As Byte) As String
Dim s As String = _
"0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZabcdefgh ijklmnopqrstuvw xyz"
Dim sb As New StringBuilder
'It's back inside the function but still only gets called once.
Static r As Random = Nothing

If r Is Nothing Then
'4 bytes needed to make an Integer (0 to 3).
Dim seed() As Byte = New Byte(3) {}
Dim rng As New RNGCryptoServic eProvider
'set the byte contents of seed() to random values.
rng.GetBytes(se ed)
'use BitConverter to convert the bytearray to an Integer
r = New Random(BitConve rter.ToInt32(se ed, 0))
End If

Do
sb.Append(s.Cha rs(r.Next(0, 61)))
Loop While sb.Length < Stringlength

Return sb.ToString

End Function
///

"Crirus" <Cr****@datagro up.ro> wrote in message
news:eX******** ******@tk2msftn gp13.phx.gbl...
So Random class is much better than rnd function?

--
Ceers,
Crirus

------------------------------
If work were a good thing, the boss would take it all from you

------------------------------

"Mick Doherty" <md*******@nosp am.ntlworld.com > wrote in message
news:Qa******** *********@newsf ep1-win.server.ntli .net...
What's that CInt("0"c)? doesn't work here although Asc("0"c) does, as does Asc("0").
What's that Machine.Shift.L eft? doesn't work here. I understand what it's meant to do though.(number between 0 and &HFFFFFFFF).
I like that Random class, hadn't seen that before, but, according to the
documentation, for best performance Random should only be created once.
StringBuilder.A ppend is faster than String +=.
You missed the LCase characters.

My much simpler version of that same function, with default time based
seeding of Random:

Private r As New Random
'I think 255 characters should be enough, although there's no reason that 'you can't use Integer or Short instead of Byte, and have more.
Private Function RandomString(By Val Stringlength As Byte) As String

Dim s As String = _
"0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZabcdefgh ijklmnopqrstuvw xyz"
Dim sb As New System.Text.Str ingBuilder

Do
sb.Append(s.Cha rs(r.Next(0, 61)))
Loop While sb.Length < Stringlength

Return sb.ToString

End Function

My version generated 100000 * 255character strings in 4 secs as opposed to yours (updated to use stringbuilder and default seeding for comparison)
taking 6 secs(making the Random object a Class level Private object

reduced
this to 5 secs). Without Stringbuilder yours took 23 secs and 21 secs.

Before that Random Class I used the old Rnd function and the fastest I

could
get, even using Stringbuilder, was 28 secs.

So I learned something useful Today.
Thankyou

Mick Doherty

"One Handed Man" <Bo****@Duck.ne t> wrote in message
news:bo******** **@titan.btinte rnet.com...
Try this - OHM

Public Class StringGenerator

Public Shared Function RandomString(le ngth As Integer) As String
Const zero As Integer = CInt("0"c)
Const nine As Integer = CInt("9"c)
Const capA As Integer = CInt("A"c)
Const capZ As Integer = CInt("Z"c)

Dim guid As Byte() = Guid.NewGuid(). ToByteArray()
Dim seed As Integer = guid(0) + Machine.Shift.L eft(guid(1), 8) +
Machine.Shift.L eft(guid(2), 16) + Machine.Shift.L eft(guid(3), 24)

Dim r As New Random(seed)

Dim s As String = Nothing
Dim i As Integer
For i = 0 To length - 1
Dim n As Integer
Do
n = r.Next(zero, capZ)
Loop While Not(n >= zero And n <= nine Or(n >= capA And n <=

capZ))
s += CChar(n)
Next i

Return s
End Function 'RandomString
End Class 'StringGenerato r


Crirus wrote:
> Is there a function that return some random ID like string
> alphanumeric? Like this:
> A35sDsd1dSGsH
>
> Thanks
> Crirus



Nov 20 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2082
by: wolfgang haefelinger | last post by:
Greetings, I'm trying to read (japanese) chars from a file. While doing so I encounter that a char with length 2 is returned. Is this to be expected or is there something wrong? Basically it's this what I'm doing: import codecs f = codecs.open("ident.in",'rb','Shift-JIS') ## japanses codecs installed
1
4164
by: Wee | last post by:
String.value.length and String.value doesn't work together in a single function in IE. I've no problem running either of this, but not together at the same time. var myMessage=document.Formcalc.splitword.value; document.writeln(myMessage); var total_length=document.Formcalc.splitword.value.length; document.writeln(total_length); //missing here.
6
4799
by: ironcito | last post by:
Hello! I'm looking for a way to have a field in my database that will automatically be filled with a random 4-character alphanumeric string every time I enter a new record. Like an autonumber field, but alphanumeric and random. Could anyone tell me how to do this? Please explain it so that a newbie can do it. Thanks a lot, and have a nice day! =)
6
4068
by: chiara | last post by:
Hi everybody! I am just at the beginning as a programmer, so maybe this is a stupid question...Anyway,I need to write a function in C to generate generate all possible strings of given length given a set of characters (allowing repetitions of the same character) For example given the characters 'E' and 'H' and maximum length 3 the function should generate the sequences
2
9688
by: Pierre | last post by:
I need to check the length of a string in a textbox control. I used RegularExpressionValidator with ".{0,20}" to check if the string is between 0 and 20 characters. Is it possible to use the other validator classes to check a string's length? I tried RangeValidator but it seems that it checks for alphabetical order. Thanks for replies.
1
2920
by: Hemanth | last post by:
Hello, How do I find the first and last non-numeric char positions (using regexp) in an alphanumeric string? For example, 99ABC1A => should return 2, 6 DE8A1 => should return 0, 3 Thanks,
3
5854
by: dohyohdohyoh | last post by:
I have a programming question to generate an ordered list of alphanumeric strings of length 4. two alphabets rest numberst, etc. EG 0000-9999 then A000-Z999 then AA00 to ZZ99 then AAA0 - ZZZ9 then AAAA - ZZZZ
2
1393
by: Mufasa | last post by:
Is there anyway to generate a string that contains the name of the namespace, the object name and then the function/procedure name that is currently running. I want to use this for logging information and am getting tired of having to type/cut-paste the things. If I can't get it all, can I get at least some of it? TIA - Jeff.
3
15543
by: ghjk | last post by:
I want to expire user account in my php application. Below is my code . But i got "mktime() expects parameter 6 to be long, string given in ". Could anyone tell me what is wrong? Please.. list($year, $month, $day) = split('', $Valid_From); $daystoadd="$Validity_Period"; $hours=$daystoadd * 24; $newdate=date("Y-m-d", mktime($hours, 0, 0, $month, $day, $year)); $today = date("Y-m-d"); if($newdate>$today)...
1
4890
by: shalabh6 | last post by:
Hi, A js file containing a function which is passing an alphanumeric string to another function in the same file, the second funtion requires 4 parameters to pass from the first function. The first three are the number and the last one is the alphanumeric string , but when I apply the fourth parameter , it throws out an error Expected';' The value in the varval parameter are like '2 xyz', '4 abc' The calling fucntion is being called...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.