Convert numbers in a string to array in visual basic - arrays

I am inputing numbers separated by commas. I need to store these numbers in an array of double elements, ignoring any other character the user has input. But the problem is that TextBox indices and array indices are different, and also 2.4 is stored as each separate elements.
For example, I have a string like this
"1,2.4,5.4,6,2"
How can I convert this to an array with elements
(1),(2.4),(5.4),(6),(2)

Utilizing the String.Split() function and combining that with a For-loop should give you the result that you want.
This will also check if it actually is a number or not, to avoid errors:
Public Function StringToDoubleArray(ByVal Input As String, ByVal Separators As String()) As Double()
Dim StringArray() As String = Input.Split(Separators, StringSplitOptions.RemoveEmptyEntries) 'Split the string into substrings.
Dim DoubleList As New List(Of Double) 'Declare a list of double values.
For x = 0 To StringArray.Length - 1
Dim TempVal As Double 'Declare a temporary variable which the resulting double will be put in (if the parsing succeeds).
If Double.TryParse(StringArray(x), TempVal) = True Then 'Attempt to parse the string into a double.
DoubleList.Add(TempVal) 'Add the parsed double to the list.
End If
Next
Return DoubleList.ToArray() 'Convert the list into an array.
End Function
The Separators As String() parameter is an array of strings that the function should split your string by. Every time you call it you can initialize a new array with the separators you want (a single separator is fine).
For example:
StringToDoubleArray("1,2;3", New String() {",", ";"})
The above will split by commas (,) and semicolons (;).
Example usage for your purpose:
Dim Values As Double() = StringToDoubleArray(TextBox1.Text, New String() {","}) 'Uses a comma as the separator.
Update:
Online test: http://ideone.com/bQASvO

Related

Populating an array from an input file

I'm an extreme beginner with vb and coding in general and this is my first post on this site. I am running into a wall with a project I am working on. This is the smallest block of code in the project but all other functions will pull from the array I'm trying to populate. Essentially I need to populate an array with numbers representing the prices of DVDs from a .txt file. The .txt file is formatted as follows:
The Lord of the Rings, 10.50
Avatar, 5
Gangs of New York, 7.5
etc
Where 10.50 is the value I would want to assign to dblPrices(0). It is required to not change the format of the .txt file. So far, this is what I was using but when testing the output I'm getting back 0's:
'Declare variables.
Dim intCount As Integer = 0
Dim strLine As String
'Open the file for input.
inFile = IO.File.OpenText("availableDVDs.txt")
'Remove alpha characters from string, assign numeric values to array representing price.
Do Until inFile.Peek = -1
strLine = inFile.ReadLine.ToUpper.Replace("[A-Z]", "")
strLine = strLine.Replace(" ", "")
strLine = strLine.Replace(",", "")
Double.TryParse(strLine, dblPrices(intCount))
intCount += 1
Loop
This is related to a school project so I'm not necessarily looking for someone to do my work for me, but perhaps point me in the right direction. Thank you!
If you use List(Of T) (The T stands for Type, like Integer or String or your own type) then you don't need to know the size in advance like an array. Also you don't need to keep track of indexes. You can just use the .Add method and the new item is put at the end of the list.
You can get a head start on getting the data out of the file by using File.ReadAllLines which will return an array of lines in the text file. Then you can just .Split each line on the "," (comma) and use the second element of the resulting array. The little c after the comma in double quotes tells the compiler that you mean this a Char which is the datatype that .Split is expecting.
I used a Decimal datatype instead of Double. When working with money it is safer to use to get the answer you expect.
In the second code sample I used an Interpolated sting indicated by the $ preceding the string. Notice that it is very similar to String.Format only the variable is inserted directly in the braces instead of a placeholder. This is available in Visual Studio 2015 and later.
The array method...
Private Sub OPCode()
Dim Lines = IO.File.ReadAllLines("availableDVDs.txt")
Dim Prices(Lines.Count - 1) As Decimal
Dim index As Integer
Dim price As Decimal
For Each line In Lines
Dim SplitOnComma = line.Split(","c)
If Decimal.TryParse(SplitOnComma(1), price) Then
Prices(index) = price
index += 1
Else
MessageBox.Show(String.Format("Price for {0} is not valid.", SplitOnComma(0)))
End If
Next
End Sub
The list method...
Private Sub UsingList()
Dim Lines = IO.File.ReadAllLines("availableDVDs.txt")
Dim Prices As New List(Of Decimal)
Dim price As Decimal
For Each line In Lines
Dim SplitOnComma = line.Split(","c)
If Decimal.TryParse(SplitOnComma(1), price) Then
Prices.Add(price)
Else
MessageBox.Show($"Price for {SplitOnComma(0)} is not valid.")
End If
Next
End Sub
With Option Infer Off
Private Sub OPCode()
Dim Lines() As String = IO.File.ReadAllLines("availableDVDs.txt")
Dim Prices(Lines.Count - 1) As Decimal
Dim index As Integer
Dim price As Decimal
For Each line In Lines
Dim SplitOnComma() As String = line.Split(","c)
If Decimal.TryParse(SplitOnComma(1), price) Then
Prices(index) = price
index += 1
Else
MessageBox.Show(String.Format("Price for {0} is not valid.", SplitOnComma(0)))
End If
Next
End Sub

How to extract a part of array by referring start and end index just like what we do in Matlab

For example, if we have an array A.
In matlab, we just use A[a:b] to get a sub array easily,where a,b are start point and end point respectively.
Is there similar way to do it in VBA?
Thanks
Working with arrays is incredibly fast so this will probably give no discernable benefit - although I can understand how it may appeal from a coding sense than looping to fill a smaller array
Given you are working with a single element array you could:
Introduce a "marker" string inside the large array.
Join the large array with a delimiter into a single string.
Split the large array by the "marker" string, then separate the reduced string into a smaller array with the delimiter.
The code below dumps the numbers 1 to 100 into an array, and then splits it as above to pull out the first 10 records.
Sub test()
Dim bigArr
Dim subArr
Dim strSep As String
Dim strDelim As String
Dim strNew As String
Dim rowBegin As Long
Dim rowEnd As Long
strDelim = ","
strSep = "||"
'fill array with 1 to 100
bigArr = Application.Transpose(Application.Evaluate("row(1:100)"))
rowBegin = 1
rowEnd = 10
bigArr(rowEnd + 1) = strSep
'make a single string
strNew = Join(bigArr, strDelim)
'split the string at the marker
vArr = Split(strNew, strSep)
ReDim subArr(rowBegin To rowEnd)
'split the smaller string with the desired records
subArr = Split(Left$(vArr(0), Len(vArr(0)) - 1), strDelim)
End Sub

Getting full Split array into a VBA variable

Say I have a path in Range("A1") that looks like this:
/data/apps/server/
I would like to get the three elements into a variable. I've thought doing a Split() by the separator / I would get the full array:
Dim myElements()
myElements = Split(Range("A1").Value,"/")
'>>> EXPECTED: myElements is [data, apps, servers]
but I actually get a Type mismatch error on the line myElements = Split(Range("A1").Value,"/"). What does the Split function return? Does it actually return the array or it rather gives read-only access?
I would just like to get the array of the Split method without having to loop through them and build my own array, if possible of course.
Change Dim elements() to Dim elements As Variant
You need to declare it as a Variant.
Explanation:
The data in Excel cell can be anything. So use a Variant. In cases like below, you know it is a String so declare it like a String
Sub Sample()
Dim myElements() As String
Dim myString As String
myString = "aaa/bbb/ccc"
myElements = Split(myString, "/")
Debug.Print myElements(0)
Debug.Print myElements(1)
Debug.Print myElements(2)
End Sub
Split returns a String Array. You may want to see This
Edit: I have a feeling that I may confuse someone with my explanation so let me explain it a bit more.
Dim myElements() means "Declare myElements as array of Variants".
Split returns an array of Strings. Hence, the mismatch.
You can do either Dim myElements or Dim myElements as Variant or Dim myElements() as String to resolve the problem.
Here is why each one of these works:
Dim myElements and Dim myElements as Variant
Both of these means that you declare myElements as Variant. Variants are special types, which can accept anything. As such, they can accept array of strings easily. However, variants have large memory overheads and should be avoided wherever possible.
Dim myElements() as String
This means that you declare myElements as array of strings. Since this is the same type as what is returned by the Split function, it is accepted.
Ideally, if you know the return type of a function, you should specify the correct type for your variables.
So in this case, Dim myElements() as String which is the same type returned from the Split funcition.

How to count the number of words in a variable?

What I want to do is to count the number of words a variable has. It's for a hangman game, and will be separated by commas. So I'm basically hoping that the variable will look something like this:
"hang,man,group,toll,snail"
I'm planning on splitting it with the commas to create an array, but apart from that, I'm totally lost on what to do.
On the other hand, I'm more than happy to see any other suggestions for sorting out words to be used in a hangman game!
You're halfway there.
Dim wordCount as Integer = "hang,man,group,toll,snail".Split(",").Length
This splits it into an array, and then returns the number of elements in that array.
Dim Words as String = "hang,man,group,toll,snail"
Dim Word = Words.Split(",")
So the result will be .. Word(0) = "hang", Word(1) = "man" ... so on ..
use Split like so
Dim words As String() = SOMESTRING.Split(New Char() {","c})
now to find length you can
words.length ' set this to a variable or output
alternativly you can also use the words individually
words(0) ' set this to a variable or output
words(1) ' set this to a variable or output
and so on
You can easily split a string into an array by using the String.Split method.
There are a number of overloads, however the one I use most often is this one:
Dim myString as String = "hang,man,group,toll,snail"
Dim myStringArray as String()
myStringArray = myString.Split(new String { "," }, StringSplitOptions.None)
This will give you a string array of length 5.
Documentation can be found here: http://msdn.microsoft.com/en-us/library/tabh47cf.aspx
Dim Text As String
Dim i As Integer
Dim ary() As String
Text = "hang,man,group,toll,snail"
ary = Text.Split(",")
For i = 0 To UBound(ary)
MsgBox(ary(i)) 'here you will get all the words in the array
Next i
MsgBox(i) 'You will get the number of items in your array

Convert string array to double array in VB.NET

I have a string "TextLine" that contains doubles and integers. Now I want to split the string into its parts and convert the resulting string array to double. Unfortunately I get an overload resolution error (for "parse") when I try to do that. What am I doing wrong?
Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), [Double].Parse)
You can do it like this:
Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), New Converter(Of String, Double)(AddressOf Double.Parse))
However, if the string array that you are giving it contains any invalid items, that will throw an exception and fail to convert any of the items. If you want to handle invalid items and just default them to 0, you could implement your own converter, like this:
Private Function DoubleConverter(ByVal text As String) As Double
Dim value As Double = 0
Double.TryParse(text, value)
Return value
End Function
Then, you can use it like this:
Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), New Converter(Of String, Double)(AddressOf DoubleConverter))

Resources