String indexed arrays in VB .Net - arrays

I need an array indexed with strings, like this:
Dim Array ("A") as integer' <-- I need an array like this
Dim StringArray() as string = {"A","B","C","A","A","B","D"}
For each Letter in StringArray
Array(Letter) += 1
next
Results I wanted but not worked:
Array(A) = 3
Array(B) = 2
Array(C) = 1
Array(D) = 1
I, also tried List's, not working:
Dim Array As New List(Of Object)
Dim StringArray() as string = {"A","B","C","A","A","B","D"}
For each Letter in StringArray
Array(Letter) += 1
next
Is there a way count strings this way in VB .Net?

You can use a Dictionary(Of TKey, TValue) where your letters are the keys, and the values will store your totals:
Dim dict = New Dictionary(Of Char, Integer)
dict.Add("A"c, 0)
dict.Add("B"c, 0)
dict.Add("C"c, 0)
dict.Add("D"c, 0)
Dim stringArray() As Char = {"A"c, "B"c, "C"c, "A"c, "A"c, "B"c, "D"c}
For Each letter In stringArray
dict.Item(letter) += 1
Next

Related

Change a single-dimension array into a multi-dimensional array in VBA for Access

I have code to ask a user for a series of codes that then creates a single-dimensional array like this:
Dim strDaysTimes As String
Dim arrDaysTimes() As String
strDaysTimes = InputBox("What days and times do you want to schedule meetings for? (write as 6c,7b)", "Enter Days and Times")
arrDaysTimes() = Split(strDaysTimes, ",")
The number of inputs is not defined but the format is. It could be "6c,7b" or "5a,6b,7b".
I want to convert this into a multi-dimensional array that would carry the values like this (one dimension has the number portion and the other has the letter portion):
5 a
6 b
7 b
I know that I need to use a nested For...Next statements to process multidimensional arrays, but I would appreciate any suggestions.
Use ReDim:
Public Function DivideArray()
Dim strDaysTimes As String
Dim arrDaysTimes() As String
Dim DaysTimes() As String
Dim Index As Integer
strDaysTimes = InputBox("What days and times do you want to schedule meetings for? (write as 6c,7b)", "Enter Days and Times")
arrDaysTimes() = Split(strDaysTimes, ",")
ReDim DaysTimes(UBound(arrDaysTimes) - LBound(arrDaysTimes) + 1, 0 To 1)
For Index = LBound(arrDaysTimes) To UBound(arrDaysTimes)
DaysTimes(Index, 0) = Left(LTrim(arrDaysTimes(Index)), 1)
DaysTimes(Index, 1) = Right(RTrim(arrDaysTimes(Index)), 1)
Next
For Index = LBound(arrDaysTimes) To UBound(arrDaysTimes)
Debug.Print DaysTimes(Index, 0), DaysTimes(Index, 1)
Next
End Function
Input example:
a7, b8, c9
Output:
a 7
b 8
c 9
Just for the sake of the art an alternative to #Gustav 's approach with the bonus that it returns token lengths greater than 1, too.
Furthermore it profits from the fact that the Val() function is able to return
a) the starting numeric value from an input string and
b) the closing string by a split via the above numeric value as delimiter.
Public Function tokenize(ByVal s As String)
Dim arr() As String
arr() = Split(Trim(s), ",")
Dim tmp() As String
ReDim tmp(0 To UBound(arr) - LBound(arr), 0 To 1)
Dim i As Long
For i = LBound(arr) To UBound(arr)
Dim num: num = Val(arr(i))
tmp(i, 0) = num
tmp(i, 1) = Split(arr(i), num)(1)
Next
tokenize = tmp
End Function
Example call
Sub testTokenize()
'0. Get input string (e.g. "6c,7b")
Dim strDaysTimes As String
strDaysTimes = InputBox( _
"What days and times do you want to schedule meetings for? (write as 6c,7b)", _
"Enter Days and Times", _
"6c,7b")
'1. Call help function
Dim results As Variant
results = tokenize(strDaysTimes) ' << function tokenize()
'2. Show results in VB Editor's immediate window
Dim i As Long
For i = LBound(results) To UBound(results)
Debug.Print results(i, 0), results(i, 1)
Next
End Sub
The following code will help you get there.
The GetDaysAndTimes function will return a Jagged array (i.e. an array of arrays). This means that to get the Day and Time of Item 3 you would use ArrayName(2)(0) and ArrayName(2)(1) where arrayname is the name of the array you are using (arrayDaysTimes?)
The function SplitAlphaNumString allows users to enter codes such as AB23.
Option Explicit
' This function takes the string returned by your input box
Public Function GetDaysAndTimes(ByRef ipString As String) As Variant
Dim myItems As Variant
myItems = VBA.Split(ipString, ",")
Dim myDayTimes As Variant
Dim myindex As Long
For myindex = LBound(myItems) To UBound(myItems)
myDayTimes(myindex) = SplitAlphaNumString(myItems(myindex))
Next
GetDaysAndTimes = myDayTimes
End Function
Public Function SplitAlphaNumString(ByVal ipString As String) As Variant
Dim myindex As Long
For myindex = 1 To VBA.Len(ipString)
If VBA.Asc(VBA.Mid(ipString, myindex, 1)) < 58 Then
Dim myAlphas As String
myAlphas = VBA.Mid(ipString, 1, myindex - 1)
Dim myNums As String
myNums = VBA.Mid(ipString, myindex)
SplitAlphaNumString = Array(myAlphas, myNums)
Exit Function
End If
Next
End Function
Sub Test()
Dim myArray As Variant
myArray = SplitAlphaNumString("D5")
Debug.Print myArray(0), myArray(1)
End Sub

Vb.net loop value stored to an array

I have the following code which loop through all the cells of the selected row. How to store all the values in an array?
Dim selectedCellCount As Integer = dgvData.GetCellCount(DataGridViewElementStates.Selected)
Dim RowVal As String
Dim i As Integer
For i = 0 To selectedCellCount - 1
RowVal = dgvData.SelectedCells(i).Value.ToString
Next i
End Sub
There is two method one with list another with array
1- List
Dim selectedCellCount As Integer = dgvData.GetCellCount(DataGridViewElementStates.Selected)
Dim RowVal As String
Dim i As Integer
Dim list As New List(Of string)
For i = 0 To selectedCellCount - 1
RowVal = dgvData.SelectedCells(i).Value.ToString
list.Add(RowVal)
Next i
End Sub
2- Array
Dim selectedCellCount As Integer = dgvData.GetCellCount(DataGridViewElementStates.Selected)
Dim RowVal As String
Dim i As Integer
Dim arrayOfData(selectedCellCount - 1) As String
For i = 0 To selectedCellCount - 1
RowVal = dgvData.SelectedCells(i).Value.ToString
arrayOfData(i) = RowVal
Next i
End Sub
Check out a List(of string). The list is easier to use than any other type of array. Here is a good explanation:
https://www.dotnetperls.com/list-vbnet

Access VBA loop through listbox select items and add to array

I'm trying to loop through a listbox and add the contents to an array....
My code is this:
Private Sub exportfolders_Click()
Dim list As String
Dim folderlist As String
Dim folderarray() As String
'Dim i As Interger
For i = 0 To Me.selectedfolders.ListCount - 1
'folderlist = (Me.selectedfolders.Column(0, i))
'folderarray() = Join(Me.selectedfolders.Column(0, i), ",")
list = (Me.selectedfolders.Column(0, i))
folderarray() = Join(list, ",")
ReDim Preserve folderarray(i)
Next i
folderlist = folderarray
'folderarray() = Join(folderlist, ",")
MsgBox (folderlist)
End Sub
You can see the bits I have commented out, trying all sorts to get it to work. But I keep getting the message "Can't assign to array" at folderarray(i) = Join(list, ","). Any pointers as to where I am failing?
You can concatenate the list box items into a string, and then use Split() to load your array. That way, the array is sized automagically without you needing to ReDim.
I tested this code in Access 2010:
Dim folderarray() As String
Dim i As Long
Dim strList As String
For i = 0 To Me!selectedfolders.ListCount - 1
strList = strList & "," & Me!selectedfolders.Column(0, i)
Next
' use Mid() to exclude the first comma ...
folderarray = Split(Mid(strList, 2), ",")
Note I don't know what you want to do with the array after loading it. MsgBox folderarray would throw Type mismatch error. MsgBox Mid(strList, 2) would be valid, but if that's what you want, you wouldn't need the array.
1) declare the array. Take a look at https://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
2) No need of support variable
3) Assign the values to your array with the correct syntax
Private Sub exportfolders_Click()
Dim folderarray() As String
Dim i As Interger
Redim folderarray (Me.selectedfolders.ListCount-1)
For i = 0 To Me.selectedfolders.ListCount - 1
folderarray(i) = Me.selectedfolders.Column(0, i)
Next i
' Write here what you want to do with your array
End Sub
You could try something like this:
Private Sub ListToArray()
Dim folderArray() As Variant
Dim currentValue As String
Dim currentIndex As Integer
Dim topIndex As Integer
topIndex = Me.selectedfolders.ListCount - 1
ReDim folderArray(0 To topIndex, 0 To 1)
For i = 0 To topIndex
currentValue = Me.selectedfolders.Column(0, i)
folderArray(i, 0) = i
folderArray(i, 1) = currentValue
Next i
End Sub
Note my example is a multi-dimensional array which will give you the ability to add more than one item should you chose to do so. In this example I added the value of "i" as a placeholder/ index.

Why am I getting an Index Out Of Range Exception?

I am writing a Ceasaer Function that takes a string and runs it through a variant of the Ceasear cipher, and returns the encoded text. For some reason I am getting an Index Out Of Range error on an Array declared with no specific bounds. Why am I getting this exception, and how do I fix it?
VB.NET Code:
Public Shared Function Ceaser(ByVal str As String) As String
Dim r As String = ""
Dim ints() As Integer = {}
Dim codeints As Integer() = {}
Dim codedints As Integer() = {}
Dim ciphertext As String = ""
For i As Integer = 0 To str.Length - 1
Dim currentch As Integer = Map(str(i))
ints(i) = currentch 'Where exception is happening
Next
Dim primes As Integer() = PrimeNums(ints.Length)
For i As Integer = 0 To primes.Length - 1
codeints(i) = ints(i) + primes(i) - 3
Next
For i As Integer = 0 To codeints.Length - 1
Dim currentnum As Integer = codeints(i) Mod 27
codedints(i) = currentnum
Next
For i As Integer = 0 To codedints.Length - 1
Dim letter As String = rMap(codeints(i))
ciphertext += letter
Next
Return ciphertext
End Function
You have to specify the array bounds before you can acces its elements:
Dim ints As Integer(str.length-1)
will instantiate the array with n elements where n = length of string str.
(Take care: VB .NET array lengths are zero-based, so an array with 1 element is instantiated with array(0)).
You have to adopt the other arrays accordingly.

multidimentional array of strings in vb.net

I have a text file like:
[edit] the number of line is unknown, it could be hundreds of lines.
How would I store them in a multidimensional array? I want my array to look like:
sample(0)(0) = "--------"
sample(0)(1) = "Line1"
..and so on
sample(1)(0) = "--------"
sample(1)(3) = "Sample 123"
..and so on
What I have done so far was to open the file and store in a 1-dimentional array:
logs = File.ReadAllLines("D:\LOGS.TXT")
I have tried creating an Array of string like:
Dim stringArray as String()()
stringArray = New String(varNumber0)(varNumber1)
But it returns and error.
You can use File.ReadLines/File.ReadAllLines to get the lines and a simple For Each-loop to fill a List(Of List(Of String)). Then you can use
list.Select(Function(l) l.ToArray()).ToArray()
to get the String()() (jagged array):
Dim lines = File.ReadLines("D:\LOGS.TXT")
Dim list As New List(Of List(Of String))
Dim current As List(Of String)
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
list.Add(current)
Else
current.Add(line)
End If
Next
Dim last = list.LastOrDefault()
If last IsNot Nothing Then
If Not current Is last AndAlso current.Any() Then
list.Add(current)
ElseIf Not last.Any() Then
list.Remove(last) ' last line was ("----------")'
End If
End If
Dim stringArray As String()() = list.Select(Function(l) l.ToArray()).ToArray()
If you want to include the --------- in the array at the first position:
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
current.Add(line)
list.Add(current)
Else
current.Add(line)
End If
Next
Try like this but you need to customize according to you
Dim mArray(10,10) As String
Dim i As Integer = 0
For I=0 to 10
For J=0 to 10
For Each line As String In System.IO.File.ReadAllLines("file.txt")
mArray(i,j) = cmdReader.Item(line)
Next
Next
Next
Use declaration like this (this is just a generic)
Dim dim1 As Integer = 0
Dim dim2 As Integer = 0
Dim strings(,) As String
Do
dim1 = NewDimensionNumberFromFile
dim2 = NewSecondDimensionNumberFromFile
ReDim Preserve strings(dim1, dim2)
strings(dim1, dim2) = ValueFromfile
Loop While (Not EOF()) 'this will determine

Resources