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.
Related
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"
VB.NET: How to create a program to insert 10 elements in an array?
How to create another array from it but no repeated number should be inserted?
Here's an example of the concept:
Dim ary(9) As String
ary(0) = 1
ary(1) = 3
ary(2) = 5
ary(3) = 4
ary(4) = 6
ary(5) = 4
ary(6) = 3
ary(7) = 8
ary(8) = 9
ary(9) = 3
Dim newary() As String = ary.Distinct.ToArray
...but if you are not explicitly bound to using an array, a list would be much better. With an array, you'd have to limit yourself to the number of items you've instantiated the array with, or redim/resize it every time you add an element to it. A list wouldn't be limited like that and you could add new values on the fly.
Also, if all you need is distinct elements in the array, why not just check if your original array already contains a value before adding it, that way you skip having to copy the distinct values out of there..?
Or use this:
Dim lst As New List(Of String)
lst.AddRange({"1", "2", "3", "4", "5", "6", "7", "8", "9"})
Dim array As String() = lst.ToArray
It does the same as the other answer but its smaller
It doesnt get much shorter than this. You'll need to import Linq. array2 will contain 8 values since 1 and 9 are repeated.
Dim array1 As Integer() = {1, 1, 2, 3, 4, 5, 6, 7, 9, 9}
Dim array2 As Integer() = array.Distinct().ToArray()
Within the worksheet that the macro is defined in, id like to iterate through all the columns and save the ones that are filled in an array.
x = IIf(WorksheetFunction.CountA(Columns("C")) > 0, 1, 0)
This is an example of how I'd check if the column is empty. It returns 1 if the column is filled and 0 if it is empty.
Another thing that I'd like to know is how I could give and get the column name as a variable rather than hardcoded string ("C" as you see above).
Id like the array to look like:
("A", "B", "C", "E", "G", "H", "I")
This code should do the trick:
Dim DataCols() As String
Dim strTemp As String
Dim strCol As String
Dim i As Long
For i = 1 To ActiveSheet.UsedRange.Columns.Count
If WorksheetFunction.CountA(Columns(i)) > 0 Then
strCol = Columns(i).Address
strTemp = strTemp & Mid(strCol, 2, InStr(strCol, ":") - 2) & "|"
End If
Next i
strTemp = Left(strTemp, Len(strTemp) - 1) 'Trim trailing |
DataCols = Split(strTemp, "|")
The For..Next loop iterates through all columns in the active worksheet.
Using WorksheetFunction.CountA as you also used in your example it is then determined whether the current column has any data in it.
If the column contains data we get its address (Which will be a string in the format $A:$A) and use Mid(..) to get the letters between the $ character and the : character.
Append that column letter to strTemp, followed by a Pipe | which we will later use as a delimiter.
The Dynamic Array DataCols is then populated by using the Split function on strTemp to return a string array (delimited by the |s we included).
Hope this helps!
I just learn how to create an array literal in VB.NET.
Dim MyArray = New Integer() { 1, 2, 3 }
' Or
Dim MyArray() As Integer = { 1, 2, 3 }
' Or
Dim MyArray() = { 1, 2, 3 }
' Or
Dim MyArray() = { 1, 2, "A", "B" }
Now, I want to use A LITERAL ARRAY in a condition (see pseudo-code)
If 1 exists in {1,2,3,4} Then
MsgBox "Exists!"
End If
but I don't know how, seems like you have to assign it to a variable before you can use it in the condition.
Dim MyArray() As Integer = {3, 2, 3}
If (MyArray.Contains(1)) Then
MsgBox("exists!")
Else
MsgBox("does not exist!")
End If
The above code works, but I'm just wondering is there any way to do this without assigning the array literal to variable first?
Thanks in advance!
Use {1,2,3,4}.Contains(1) for this.
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}