How do you create a New array in VB.NET? [duplicate] - vb.net

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
VB.Net Initialising an array on the fly
This maybe a stupid question, but its got me exasperated. How do I declare a new array inline? Is this possible? I've tried all of the following and they all don't work.
myVar = {"a", "b", "c"}
myVar = Array(3)
myVar = Array("a", "b", "c")
myVar = New Array()
myVar = New Array(3)
myVar = New Array("a", "b", "c")

Either
Dim strings = New String() {"a", "b", "c"}
or
Dim strings() As String = {"a", "b", "c"}
should work

Related

Inconsistencies in While Loop Variables

I am in the midst of writing a simple encryptor/decryptor program and have run into a small issue. All the characters are being generated a different string of characters to uniquely identify them. These strings are meant to be all the same length but don't seem to be. The code in question: (Full code can be viewed here)
Dim genLength As Integer = 0
Dim charNow As Integer = 0
Dim charGenned As String
Dim rndGend As Integer = 0
While genLength < enhancedMode
fs.Write(arrayAll(charNow))
Dim rndString As String = ""
While rndGend < encLength
Randomize()
Dim genned As Integer = CInt(Math.Ceiling(Rnd() * 46)) + 1
charGenned = arrayAll(genned)
rndString = rndString + charGenned
rndGend += 1
End While
fs.Write(rndString & vbNewLine)
rndGend = 0
charNow = charNow + 1
genLength = genLength + 1
End While
From what I can tell this should give me the result I am looking for, but the generated strings are not at all consistent in length. A sample of the output:
alh*ph)lufe$2fz!d7c0$qfd(ol6f173#
b^i24#^v0gx%01iqrpugg8)(mqsl8%
c1km5jnz0hti&u$#rqeh5ism31t^96^
dkx&6$ok!#u#*e^x6659jpvcnn258zpi
e%y1(y3%#w9kk9&h7d6gw)w72*3c9*d)j
fy#(i4yeg0%ltj#887!x4!e32^703e4l
gj$4#5&f!!zzdkvs)v##94)*rcmroy
While the string after the letter A is 32 digits long, as is for B, and C, when you get to G, the string is only 29 characters long. It is most noticeable in the fact that the program only generates strings for characters up to numeral 5, then stops:
3%y1(y3%#w9kk9&h7d6gw)w72*3c9*d)j
4y#(i4yeg0%ltj#887!x4!e32^703e4l
5j$4#5&f!!zzdkvs)
What is going amiss here?
I just tidied up a bit and changed to the Random class which I think is much easier to use. If you declaring an array in vb.net remember it is Dim variable(ubound) As Type. ubound stands for the Upper bound of the array, the highest index so an array with 47 elements would have indexes 0-46. The ubound would be 46 Dim variable(46) As String
Private r As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Dim arrayLetters() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim arrayAll() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")"}
Dim encLength As Integer = 16
If CheckBox2.Checked = True Then
encLength = 32
End If
Dim enhancedMode As Integer = 26
If CheckBox1.Checked = True Then
enhancedMode = 46
End If
Dim genLength As Integer = 0
Dim charNow As Integer = 0
Dim charGenned As String
Dim rndGend As Integer = 0
Dim sb As New StringBuilder
While genLength < enhancedMode
sb.Append(arrayAll(charNow))
Dim rndString As String = ""
While rndGend < encLength
Dim genned As Integer = r.Next(0, 46)
charGenned = arrayAll(genned)
rndString &= charGenned
rndGend += 1
End While
sb.AppendLine(rndString)
rndGend = 0
charNow += 1
genLength += 1
End While
Dim name As String
If TextBox1.Text = "" Then
name = "KeyGenned"
Else
name = TextBox1.Text
End If
Dim path As String = Application.StartupPath & "\" & name & ".txt"
File.WriteAllText(path, sb.ToString)
Close()
End Sub

Caesar Cipher encryption VB.net

I am trying to make an encryption method in VB.net.
I plan to use arrays so you input the value and it then compares two arrays changing the value.
Console.WriteLine("Please input text")
Dim UserInput As String = Console.ReadLine
UserInput = UserInput.ToUpper()
Console.WriteLine("Original Input is " & UserInput)
Dim EncriptedText As String
Dim Numbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "23", "24", "25", "26", "27"}
Dim Letters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "}
For counter As Integer = 0 To UserInput.Length - 1
Dim pos As Integer = Array.IndexOf(Numbers, UserInput.Chars(counter))
Dim CharValue As Char = Letters.ElementAt(pos)
UserInput = UserInput + CharValue
Console.WriteLine(UserInput)
Next
Console.Read()
End Sub
It throws an error when I try to run it.
Does anyone have any idea how I could fix it?
Error : Found on The Dim CharValue As Char Line
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
I was thinking it could be because I am trying to convert numbers to chars and if so what other methods could I use?
1) You are using the wrong array to get the index of a letter, and so the wrong array to get its enciphered value.
2) When you use Array.IndexOf like that, you need to give it a string to look for rather than a char. In your code, it is returning -1 because it didn't find the char in the array of strings (once the correct array is used).
3) You're modifying the input string in the loop, I guess you meant to use a separate variable for it.
Console.WriteLine("Please input text")
Dim userInput As String = Console.ReadLine()
userInput = userInput.ToUpper()
Console.WriteLine("Original input is " & userInput)
Dim numbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "23", "24", "25", "26", "27"}
Dim letters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "}
Dim encryptedText As String = ""
For counter As Integer = 0 To userInput.Length - 1
Dim pos As Integer = Array.IndexOf(letters, (userInput.Chars(counter)))
Dim cipherValue As String = numbers.ElementAt(pos)
encryptedText = encryptedText & cipherValue
Console.WriteLine(encryptedText)
Next
Console.Read()
Please note that it is usual to start variable names with a lowercase letter.
Now that you can get output, you can go on to find the other problems with the code :)

VB.NET Randome Function to replace values

I have a Random Function in vb.net like this which returns the 6-digit alphanumeric string like this.
Public Function rand() As String
Dim rng As Random = New Random
Dim sb As New StringBuilder
' Selection of pure numbers sequence or mixed one
Dim pureNumbers = rng.Next(1, 11)
If pureNumbers < 7 Then
' Generate a sequence of only digits
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, digits.Length)
sb.Append(digits.Substring(idx, 1))
Next
Else
' Generate a sequence of digits and letters
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, 36)
sb.Append(s.Substring(idx, 1))
Next
End If
Return sb.ToString()
End Function
The problem is that when it returns 0 or O or 1 or I and so on {"1", "I", "O", "0", "5", "S", "7"}
I want to replce these character with 'A' and then should return the final random string.
If I understand you correctly, you want something like this (untested):
dim exceptionLetters = _
{"1", "I", "O", "0", "5", "S", "7"}
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, 36)
Dim ltr = s.Substring(idx, 1)
if (exceptionLetters.Contains(ltr))
Return sb
End If
sb.Append(ltr);
Next

Every time I generate a string, then close the program and generate again its the same

Well I have made this random string generate but I have recently noticed a fatal flaw. When I generate a random string, close the program and generate another random string it is the same as the first generation. Here is the code:
Public Function RandomString(ByVal length As Integer) As String
Dim strb As New System.Text.StringBuilder
Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim UpperBound As Integer = UBound(chars)
For x As Integer = 1 To length
strb.Append(chars(Int(Rnd() * UpperBound)))
Next
Return strb.ToString
End Function
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
Try
System.Diagnostics.Process.Start("Link Removed!")
Catch
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim repeatCnt As Integer
'Check for valid numeric entry
If Integer.TryParse(TextBox2.Text, repeatCnt) Then
For repeatIdx As Integer = 1 To repeatCnt
Dim rndstring As String
'Generate random string...
rndstring = RandomString(24)
'...and append to text box with a line break
RichTextBox1.Text &= rndstring & vbCrLf
Next
Else
MessageBox.Show("Please enter a valid integer number in the text box")
End If
End Sub
Your problem is that you're running Rnd() instead of using the Random class.
In order to keep Rnd() from giving the same sequence of "random" numbers every time, Random.Next() should be called (in order to use the machine clock for the initial value / seed).
So in your case:
Dim random As New System.Random()
Public Function RandomString(ByVal length As Integer) As String
Dim strb As New System.Text.StringBuilder
Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim UpperBound As Integer = UBound(chars)
For x As Integer = 1 To length
strb.Append(chars(Int(random.Next(UpperBound)))
Next
Return strb.ToString
End Function
Try generating a random string like this:
Public Shared Function GeneratePass() As String
Dim unique As Guid = Guid.NewGuid
Return unique.ToString.Substring(1, 6)
End Function

VB.Net Filter Array Equivalent From VB6

Been googling for an hour and can't seem to find the answer. The following will remove "stupid" and prints out "hello world"
Dim arr As Variant: arr = Array("hello", "stupid", "world")
Dim newArr As Variant: newArr = Filter(arr, "stupid", False)
Debug.Print Join(newArr, " ")
What is the VB.Net equivalent for Filter? Any help would be greatly appreciated! Edit: (I'm looking for a 2.0 NET Framework solution)
Something like this perhaps (Assumes VB 10):
Dim arr As String() = {"hello", "stupid", "world"}
Dim filteredArray = (from s in arr
Where s <> "stupid"
Select s).ToArray()
An alternative is to use Except (which is available in .Net 3.5):
Dim words As String() = {"hello", "stupid", "world"}
Dim excludedWords As String() = {"stupid"}
Dim filteredArray = words.Except(excludedWords).ToArray()
For .NET 2.0 you can use the Array.FindAll method, like this:
Dim arr As String() = New String() {"hello", "stupid", "world"}
Dim newArr As String() = Array.FindAll(arr, AddressOf RemoveElements)
Using this predicate:
Private Shared Function RemoveElements(ByVal s As String) As Boolean
Return Not s.Equals("stupid")
End Function