TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to VBNET

VB.NET Random Lowercase Letter

Generate a random lowercase letter with Random, Asc and Chr.
Random lowercase letter. In ASCII there are 26 lowercase letters. We cannot generate these directly with the Random class. But we can use a Function to get them.Random
Chr, Asc. With VB.NET helper functions like Asc and Chr we convert the Integer returned by Random's Next Function. We manipulate the value of the random number.
Here is the example. We introduce a GetLetter Function. This returns a Char. We use a Random class instance field. We call Next() on the Random class.

Argument 1: We use 0 as the first argument to Next(). The 0 will correspond to the lowercase letter "a."

Argument 2: We use 26 as the second argument. Our last letter "z" has the value 25. With Next, the second argument is exclusive.

VB.NET program that generates random lowercase letter Module Module1 ' Used for GetLetter function. Dim _random As Random = New Random() Function GetLetter() As Char ' Get random number between 0 and 25 inclusive. ' ... The second argument 26 is exclusive. ' ... This corresponds to an ASCII char. Dim number As Integer = _random.Next(0, 26) ' Convert lowercase "a" to an Integer with Asc. ' ... Use this value to offset the number we generated. ' ... Convert back to a Char with Chr. Dim letter As Char = Chr((Asc("a"c) + number)) Return letter End Function Sub Main() ' Use our GetLetter function 5 times. For i As Integer = 0 To 4 Dim letter = GetLetter() Console.WriteLine(letter) Next End Sub End Module Output v s s i q
With a Random field, we avoid repeating random sequences. When a method like GetLetter is called many times, it is important to avoid creating a new Random each time.
Some testing. After running this program many times, I find that it generates "a" through "z." And no other chars appear to be generated.
Some uses. Random lowercase letters can be used alongside a class like StringBuilder. We can generate random strings in this way.StringBuilderStrings
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf