vb 2008 set array items with one line code - vb.net

hello
Im using VB 2008
is it possible to set array items with one line code?
for example, can i do something like:
Dim array = Array("a", "b", "c", "d")
instead of:
Dim array()
array(0) = "a"
array(1) = "b"
array(2) = "c"
array(3) = "d"
thanks

You can use the following to initialize an array with explicit members.
Dim array As String() = New String(){"a", "b", "c", "d"}
This can be done with any type.

Yes using the below format:
Dim boolArr As Boolean() = New Boolean() {True, True, False, True}

Related

Pick random value from string array

How do I make the following code input either "Jack" or "John" randomly in cell A1? Currently, the result is always "2":
Sub RandomNames ()
Dim UserNames(1 To 2) As String
UserNames(1) = "Jack"
UserNames(2) = "John"
Range("A1").Value = Application.WorksheetFunction.RandBetween(LBound(UserNames), UBound(UserNames))
End Sub
Try using randbetween on the array.
Range("A1").Value = UserNames(Application.RandBetween(LBound(UserNames), UBound(UserNames)))

VB - Substitution of letters

so I am making a decryption software that allows the user to input some text and then they can swap out letters in the program. For example, there is a drop down box that allows you to swap all the "O"'s in a user input to "W". So in the input "Stack overflow" the output would be "Stack wverflww".
However, my problem is is that when the user chooses a second letter to change, that has already been swapped, it causes a problem. For example, after the first above example has occurred, if the user then wanted to then change all the "W"'s in their input to "A"'s the output would be "stack averflaa". However, what I'm looking for the code to do is give an output of "Stack wverflwa". So only the original "W"'s of the user input are changed to the letter "A".
I hope the above makes sense.
Someone suggested using a two dimensional array to reassign the letters new letters and I am able to do this, but I have no idea how to then put this into my code and get it working. Below is my code and thank you to anyone who can help me.
Dim chooseLetter, replaceLetter, words2
chooseLetter = selectLetterCombo.Text
replaceLetter = replaceLetterCombo.Text
words2 = UCase(textInputBox.Text)
Dim replaceList As New List(Of String)
For Each z In words2
If z = chooseLetter Then
replaceList.Add(replaceLetter)
Else
replaceList.Add(z)
End If
Next
letterReplaceBox.Text = ""
For Each f In replaceList
letterReplaceBox.Text = letterReplaceBox.Text & f
Next
note: selectLetterCombo.Text is the letter chosen by the user that they want to replace and replaceLetterCombo.Text is the letter chosen by the user that they want to swap the first chosen letter with. Also, textInputBox.text is the text the user has inputted.
Thank you!
You should be able to keep a list of the index of the character that changed and check that before making another change.
'List to keep track of changed character index
Dim replacedCharsList As New List(Of Integer)'member variable
Dim chooseLetter, replaceLetter, words2
chooseLetter = selectLetterCombo.Text
replaceLetter = replaceLetterCombo.Text
words2 = UCase(textInputBox.Text)
Dim replaceList As New List(Of String)
Dim i As Integer
For i = 1 To Len(words2)
'remove the for each and go with a straight for loop to keep track if the index
If Mid(words2, i, 1) = chooseLetter Then
'check to see if we have already replaced this character via the index position
If replacedCharsList.Contains(i) = False Then
'we have not changed this so add the replacement letter and update our index list
replaceList.Add(replaceLetter)
replacedCharsList.Add(i)
Else
'we have already changed this character so just add it as is
replaceList.Add(Mid(words2, i, 1))
End If
Else
replaceList.Add(Mid(words2, i, 1))
End If
Next
letterReplaceBox.Text = ""
For Each f In replaceList
letterReplaceBox.Text = letterReplaceBox.Text & f
Next
I have an answer, but you're really not going to like it:
Option Infer On
Option Strict On
Imports System.Text.RegularExpressions
Module Module1
Dim swaps As New Dictionary(Of Char, Char)
Function DoSwaps(originalText As String, swapLetters As Dictionary(Of Char, Char)) As String
Dim newText As String = ""
For Each c In originalText
If swapLetters.ContainsKey(c) Then
newText &= swapLetters(c)
Else
newText &= c
End If
Next
Return newText
End Function
Sub Main()
Console.Write("Enter the text to be altered: ")
Dim t = Console.ReadLine()
Dim exitNow = False
Do
Console.Write("Enter the letter to swap from and the letter to swap to, or a blank line to quit: ")
Dim s = Console.ReadLine()
If s.Trim().Length = 0 Then
exitNow = True
Else
Dim parts = Regex.Matches(s, "([A-Za-z])")
If parts.Count >= 2 Then
Dim letter1 = CChar(parts.Item(0).Value)
Dim letter2 = CChar(parts.Item(1).Value)
If swaps.ContainsKey(letter1) Then
swaps.Item(letter1) = letter2
Else
swaps.Add(letter1, letter2)
End If
Console.WriteLine(DoSwaps(t, swaps))
End If
End If
Loop Until exitNow
End Sub
End Module
... unless you'd like to learn about the Dictionary class to understand how it works. I used a simple regular expression to parse the user input, but if you're using dropdowns to select the letters then that would just be bonus learning if you explore it.
The essential feature is that you keep the original string (t in the above code) and apply the transformation (I named it DoSwaps) to that each time, not to the previously transformed string.
These two functions will do the job, although there is no allowance for punctuation, just spaces.
Private Function EncryptText(str As String) As String
Dim swapletters() As String = {"l", "s", "d", "f", "g", "h", "j", "k", "a", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "z", "x", "c", "v", "b", "n", "m"}
Dim encryptedText As String = ""
For Each letter As Char In str
If letter = " "c Then
encryptedText = encryptedText & " "
Else
Dim charactercode As Integer = Asc(letter) - 97
encryptedText = encryptedText & swapletters(charactercode)
End If
Next
Return encryptedText
End Function
Private Function DecryptText(str As String) As String
Dim swapletters As New List(Of String) From {"l", "s", "d", "f", "g", "h", "j", "k", "a", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "z", "x", "c", "v", "b", "n", "m"}
Dim decryptedText As String = ""
For Each letter As Char In str
If letter = " "c Then
decryptedText = decryptedText & " "
Else
Dim character As String = Chr(swapletters.IndexOf(letter) + 97)
decryptedText = decryptedText & character
End If
Next
Return decryptedText
End Function
To use them, declare a string to hold the return value of each function
Dim etext As String
etext = EncryptText("disambiguation is the root of all evil")
results in etext being "faplrsajxlzayt ap zkg oyyz yh lee gcae"
and
Dim dtext As String
dtext = DecryptText("faplrsajxlzayt ap zkg oyyz yh lee gcae")
results in "disambiguation is the root of all evil"

short way of cheeking multiple string in VBA

What is shortcut of checking string value like this.
If midtxt = "a" Then
midtxt = "apple"
ElseIf midtxt = "b" Then
midtxt = "ball"
ElseIf midtxt = "c" Then
midtxt = "cat"
.....
ElseIf midtxt = "z" Then
midtxt = "zebra"
End If
MsgBox midtxt
Is there any way I can do this using two arrays.
[a, b, c....z] and [apple, ball, cat.....zebra]
Edit
I need reproducible function for my task.
I think a for apple is not right example for me.
This is updated array for me.
[ap, bl, ca,... zr] [apple, ball, cat... zebra]
means the two letter code is derived from the corresponding string but it is not uniformly derived.
A dictionary may be worthwhile here, as long as the [a, b, ...z] set is unique.
In the VBA IDE, go to Tools, References, and select Windows Scripting Runtime.
Public gdctAnimals As Dictionary
Public Sub SetUpAnimalDictionary()
Set gdctAnimals = new Scripting.Dictionary
gdctAnimals.Add "a", "apple"
gdctAnimals.Add "b", "ball"
gdctAnimals.Add "c", "cat"
gdctAnimals.Add "z", "zebra"
End Sub
Public Sub YourProc(midtxt As String)
If gdctAnimals Is Nothing Then
SetUpAnimalDictionary
End If
If gdctAnimals.Exists(midtxt) Then
MsgBox gdctAnimals(midtxt)
Else
MsgBox "Item not found in dictionary", vbExclamation
End if
End Sub
Use the Select Case or Switch function
Function SwapString(strInput As String)
SwapString= Switch(strInput = "a", "Apple", strInput = "b", "Banana", strInput = "c", "Cherry")
End Function
In your case, if you can only have 26 combinations (a-z) the easiest way is to do this:
Public Function ReturnString(strIn As String) As String
Select Case strIn
Case "a"
ReturnString = "apple"
Case "b"
ReturnString = "ball"
Case "c"
ReturnString = "cat"
' .............
Case Else
ReturnString = "UNKNOWN"
End Select
End Function
and you call your fonction like this
MyLongString = ReturnString "a"
But there are many more possibililities that I won't detail because you have not detailed enough your question:
You can use 2 arrays or a 2D array
you can use an array of private types
you can use a dictionary as specified in another answer
No need for an external component or tedious population, you are looking for something based on an ordinal value; a=>z is the character code range 97=>122 so you can use a simple efficient array lookup by converting the character code to a value within the bounds of the array:
'//populate (once)
Dim map() As String: map = Split("apple,ball,cat,...,zebra", ",")
'//lookup
midtxt = "a"
midtxt = map(Asc(Left$(midtxt, 1)) - 97)
'=>apple
midtxt = "c"
midtxt = map(Asc(Left$(midtxt, 1)) - 97)
'=>cat
If needed check the value starts with a character first with if midtxt like "[a-z]*" then ...

VBA Recursion and hashes

I have a bit of a dilema. I am receiving an array of arrays that contains a string in the first element of an array that denotes a hash {HASH}. I dont know the structure of the array of arrays it can be different based upon the result of different calls. An example of the data is as follows:
[ [ "{HASH}", 1000, ["{HASH}", "A", 100], ["{HASH}", "B", 150], ["{HASH}", "C", 200] ],
[ "{HASH}", 1001, ["{HASH}", "D", 101], ["{HASH}", "E", 151], ["{HASH}", "F", 201] ]
]
The hash should then be as follows:
{1000}{A}=100
{1000}{B}=150
{1000}{c}=200
{1001}{D}=101
{1001}{E}=151
{1001}{F}=201
I have written the following function to be called recurrsively to output the entries in the arrays this is fine, but I need to put this into a Hash as defined and this is where it is failing, because as it is called recursively the hashes are reset etc:
Public Function ProcessObjOrArray(Obj As Variant, key As String, ByRef hashIn, HashCreated As Boolean) As Variant
Dim sKey As String
Dim i As Integer
Dim objRes As Variant
If HashCreated = False Then
Dim hash
HashCreated = True
Set hash = CreateObject("Scripting.Dictionary")
End If
If IsArray(Obj) Then
For i = 0 To UBound(Obj, 1)
objRes = ProcessObjOrArray(Obj(i), sKey, hash, HashCreated)
If (objRes = "{HASH}") Then
i = i + 1
sKey = Obj(i)
End If
Next i
If key <> "" Then
Debug.Print "Adding {" + key + "}=AllTheStuff"
Set hash.Item(key) = hashIn
Dim a
a = hash.Item(key)("Enabled")
Exit Function
End If
Else
If key <> "" Then
Debug.Print "Adding {" + key + "}=" + CStr(Obj)
hash.Item(key) = Obj
Else
ProcessObjOrArray = Obj
End If
End If
End Function
The Object passed in is obviously the array I defined above. If someone has a smart way of doing this it would be much appreciated.
I solved the issue, by using a hash passed in and at the end point, creating a new hash which is a copy of the hash passed in, and then finally reset the hash passed in and set is key and value = to the hash I copied. This successfully creates the Hash of hashes

Find Value on Array by Index on VB.Net

How to find a value on an array by it's index on VB.Net?
// INDEX: 0 1 2 3 4
Dim DataArray(4) as Integer = {"A", "B", "C", "D", "E"}
Then, I randomize a number from 0 to 4. For example, when I got 3, then I will get D value on the array based on the randomize number. How can I do that? Thank you.
You can just access the value by having the index after the array name
Dim letter As String = DataArray(YourRandNumber)
Also there is a problem with your array, DataArray is declared as an integer array but storing alphabet, so you should change it to
Dim DataArray(5) As String = {"A", "B", "C", "D", "E"}
or
Dim DataArray(5) As Char= {"A"c, "B"c, "C"c, "D"c, "E"c}
The little c after "A" means it is a character
By what I think you mean, you should have some code like (for example in a console-style form):
Randomize()
Console.writeline(DataArray(math.ceiling(Rnd() * [upperbound)))
This will return a random character.